我正在開發一個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」。 –