2015-04-04 95 views
0

我想實現一個IP掃描儀,讓我們說我有這樣的代碼:IP掃描幫助 - 線程?

// Background Task: Scan network 
class BackgroundScan extends AsyncTask<Void, Icmp_scan_result_params, Void> { 

    // Process 
    @Override 
    protected Void doInBackground(Void... params) { 

     // Load intervals 
     long start_interval = scanner.info.get_network_bounds(false); // Start IP address converted to decimal 
     long end_interval = scanner.info.get_network_bounds(true); // End IP address converted to decimal 

     // Perform scan - Skip network, broadcast and gateway address: 
     for (long ip_decimal=start_interval+1; ip_decimal < end_interval; ip_decimal++) { 
      // Skip default gateway 
      if (ip_decimal == info.ip_to_long(info.default_gateway)) { 
       continue; 
      } 
      // Convert the IP address to string 
      final String ip = info.long_to_ip(ip_decimal); 
      // Start and run new thread 
      new Thread(new Runnable() { 
       @Override 
       public void run() { 

        boolean is_reachable = scanner.icmp_scan(ip); 
        Icmp_scan_result_params _params = new Icmp_scan_result_params(ip, is_reachable); 
        publishProgress(_params); 
       } 
      }).start(); 
     } 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate (Icmp_scan_result_params... _params) { 
     // ... 
    } 
} 

掃描方法在這裏:

public boolean icmp_scan(String ip) { 
    for (int i=0; i<4; i++) { 
     // Send ping command *ROOT* 
     try { 
      Process p1 = Runtime.getRuntime().exec("ping -c 1 "+ip); 
      int result = p1.waitFor(); 
      // Positive match 
      if (result == 0) { 
       return true; 
      } 
     } catch (IOException e) { 
     } catch (InterruptedException e) { 
     } 
    } 
    return false; 
} 

但問題是,應用程序崩潰的可能是因爲太,許多執行線程一次(工作正常,5線程左右)。我該如何實現這一點,以確保應用程序始終能夠在任何設備上順利運行,這是什麼纔是正確和快速的方式?感謝幫助!

回答

0

爲什麼使用異步任務和doInBackground的線程? doInBackground已經在自己的線程上。你可能甚至不需要異步任務。

您可以只使用一個線程並在run()內部調用icmp_scan,而像threadIsNotStopped這樣的標誌爲真。或者,如果要使用多個線程,請在實現runnable的類中包裝icmp_scan的功能,傳遞分區的IP地址範圍,並使用ExecutorService。見http://developer.android.com/reference/java/util/concurrent/ExecutorService.htmlhttp://codetheory.in/android-java-executor-framework/

當你需要更新UI,你可以通過做onPostExecute如下:

Handler uiCallback = new Handler(Looper.getMainLooper()); 
uiCallback.post(new Runnable() { 
    @Override public void run() { 
    // will run on ui thread 
    } 
}); 
+0

u能幫助我把代碼放在一起請? – 2015-04-04 14:39:30