我想實現一個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線程左右)。我該如何實現這一點,以確保應用程序始終能夠在任何設備上順利運行,這是什麼纔是正確和快速的方式?感謝幫助!
u能幫助我把代碼放在一起請? – 2015-04-04 14:39:30