工具-网络

Android 使用ping判断网络/WIFI连接是否可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Android 使用ping判断网络/WIFI连接是否可用
*/
public boolean isNetworkOnline() {
Runtime runtime = Runtime.getRuntime();
Process ipProcess = null;
try {
//ping -c 5 -w 4 api.597.com
//-c 后边跟随的是重复的次数,-w后边跟随的是超时的时间,单位是秒,不是毫秒
ipProcess = runtime.exec("ping -c 5 -w 4 api.597.com");
InputStream input = ipProcess.getInputStream();

BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
DebugLog.log(stringBuffer.toString());

int exitValue = ipProcess.waitFor();
if (exitValue == 0) {
//WiFi连接,网络正常
return true;
} else {
if (stringBuffer.indexOf("100% packet loss") != -1) {
//网络丢包严重,判断为网络未连接
return false;
} else {
//网络未丢包,判断为网络连接
return true;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
if (ipProcess != null) {
ipProcess.destroy();
}
runtime.gc();
}
return false;
}