IP扫描帮助 - 线程?
问题描述:
我想实现一个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线程左右)。我该如何实现这一点,以确保应用程序始终能够在任何设备上顺利运行,这是什么才是正确和快速的方式?感谢帮助!
答
为什么使用异步任务和doInBackground
的线程? doInBackground
已经在自己的线程上。你可能甚至不需要异步任务。
您可以只使用一个线程并在run()
内部调用icmp_scan
,而像threadIsNotStopped
这样的标志为真。或者,如果要使用多个线程,请在实现runnable
的类中包装icmp_scan
的功能,传递分区的IP地址范围,并使用ExecutorService
。见http://developer.android.com/reference/java/util/concurrent/ExecutorService.html和http://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
}
});
u能帮助我把代码放在一起请? – 2015-04-04 14:39:30