InetAddress 的示例代码:
通过 InetAddress.getByName(ip).isReachable(timeout) 的方法可以ping ip 或者www.baidu.com的方式来检测网络是否可以用,但是遇到了一直返回false的问题。我这里是权限的问题
private static final boolean isNetworkReachable(String hostname) {
try {
Log.d(TAG, "hostname=" + hostname);
InetAddress address = InetAddress.getByName(hostname);
if (address.isReachable(3000)) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(hostname + "网络不可达!");
e.printStackTrace();
return false;
}
}
解决方案1:添加上网络相关的权限测试OK
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
我这里的问题加上网络相关的权限就好了,但是网上很多人说这个InetAddress 方法去ping ip的方式不太可靠,经常会命令去ping可以平通但是用InetAddress去ping 返回false,所以保险起见我们使用的时候可以在false时再去命令去ping 验证一下,这样就万无一失了。
解决方案2:InetAddress 失败的时候Runtime.getRuntime().exec 方法去ping,这样有个双保险
private static final boolean isPingIPReachable(String hostname) {
try {
return 0 == Runtime.getRuntime().exec("ping -c 1 " + hostname).waitFor();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
return false;
}
}