Android如何测试网络连通性

Android如何测试网络是否可用

  • 通过执行ping命令并获取命令的返回值,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static boolean isNetPingUsable(){
Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("ping -c 1 www.baidu.com");
int ret = process.waitFor();
if(ret == 0){
return true;
}else{
return false;
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}

ret=0时:当前网络可用
ret=1时:需要网页认证的wifi
ret=2时:当前网络不可用