简体   繁体   中英

Lots of Threads a Handler and little experience

Im trying to make a list of local machines connected to a wifi. The easy way to do this, is to ping every IP from abc1 to abc255, but we all know that would take "forever".

Therefore I'd like to use Threads!

What I have is a MainActivity that contains this:

list = (ListView) findViewById(R.id.list);
ipList.add("Nothing yet");

adapter = new ArrayAdapter<String>(this, R.layout.simplerow, ipList);
list.setAdapter(adapter);

networkList = new NetworkList(); //This is the shared list between the Threads

for(int i = 1; i<255; i++){  //Tries to ping the range of IP's

    Ping ping = new Ping(localIP + i, networkList)
    new Thread(ping).start();
}

The class Ping implements Runnable:

public void run() {
  try {
    InetAddress address = InetAddress.getByName(IP);

    if(address.isReachable(2000)){
        synchronized(networkList){
            networkList.addIP(address.getHostAddress());
            MainActivity.handler.sendEmptyMessage(0); //probably wrong
        }
    }
  } catch (Exception e) {}
}

Im not sure if the usage of synchronize is correct, but please hang on! The class NetworkList is where the synchronized stuff happends:

public synchronized void addIP( String IP ){
    foundIPs.add(IP);
}

public synchronized ArrayList<String> getIPList(){
    return foundIPs;
}

OK. Back to the MainActivity :

This is probably very wrong, but its what Ive managed to do:

    handler = new Handler() {
        public void sendEmptyMessage(android.os.Message msg) {
            adapter.clear();
            synchronized(networkList){
                ipList = networkList.getIPList();
            }
            adapter.notifyDataSetChanged();
        }
    };

What is wrong here? I want the list to be updated immediately as a thread gets a respond on the ping. In other words, I want to see the ListView expand as new IPs are found, not just retrieve the complete list when the ping process is done.

what i think is the problem is that the adapter itself doesn't get a reference to the new list of ip addresses , so it probably looks at the oldest one which has no entries.

i can see it by looking at the code:

adapter = new ArrayAdapter<String>(this, R.layout.simplerow, ipList);
...
ipList = networkList.getIPList();

With ipList = networkList.getIPList(); you're creating a new list, one that the array adapter doesn't know anything about. You should make calls directly on the adapter, such as ArrayAdapter.add or ArrayAdapter.addAll().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM