通过networkInfo.isAvailable()来判断网络是否连接,其实是不准确的,这个方法只能判断网络是否就绪,并不能判断网络是否真正连接。有一种情况,相对于Android手机 手机开热点,连接手机wifi,再断开手机数据,此时wifi连接并没有断开,只是并不能上网,此种假网情况发生时,isAvailable()仍会返回true。
解决思路:代码里请求网络,是否真正能上网,不停ping网络
解决办法:
public static final boolean isPing() {
String result = null; // 为了看log日志,可不加
try {
String ip = "www.baidu.com"; // 百度网址
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
LogUtils.d(TAG, "result----" + result);
}
return false;
}