我正在开发一个Android应用程序,我必须发现WiFi网络中的每个主机,我已经实现了一个功能,可以“ping”1和1之间的所有IP地址某个网络的255个。如何发现Android中的WiFi网络中的主机(JAVA)
这个解决方案工作完美,但有一个问题,执行时间..每当我开始我的应用程序,我等待大约256秒,它太长了,我不能等待这个时间。
这是我的源代码(我发现栈这段代码,我修改了代码,在我的条件,工作):
public class ScanNetwork {
ArrayList <String> hosts;
int i;
boolean finish = false;
public ArrayList <String> ScanNetwork(String ipAddress) {
hosts = new ArrayList <String>();
final String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
for (i = 0; i < 256; i++) {
String currentHost = subnet + "." + i;
Process p1 = null;
int returnVal = 0;
try {
p1 = Runtime.getRuntime().exec("ping -w 50 -c 1 " + currentHost);
returnVal = p1.waitFor();
} catch (IOException e) {
System.out.println("Log: " + e.toString());
} catch (InterruptedException e) {
System.out.println("Log: " + e.toString());
}
boolean reachable = (returnVal == 0);
if (reachable) {
if (!hosts.contains(currentHost)) {
hosts.add(currentHost);
System.out.println(currentHost);
}
}
}
return hosts;
}
}
此源代码是完美的,但执行时间过长,还有其他方式获取网络中的所有主机?
我该如何解决这个问题?
请参阅本[链接](http://stackoverflow.com/questions/ 36277912 /如何对扫描的IP-in-的Android/36278723#36278723)。它可能会帮助你。只需将超时时间从5秒增加到20秒。它将为您提供本地网络中的所有“IP”。 –