原理类似 电脑ping命令
public static boolean isNetworkOnline() {
Runtime runtime = Runtime.getRuntime();
Process ipProcess = null;
try {
ipProcess = runtime.exec("ping -c 5 -w 4 223.5.5.5");
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);
}
int exitValue = ipProcess.waitFor();
if (exitValue == 0) {
//WiFi连接,网络正常
return true;
} else {
if (stringBuffer.indexOf("100% packet loss") != -1) {
XLog.showArgsInfo("网络丢包严重,判断为网络未连接");
return false;
} else {
XLog.showArgsInfo("网络未丢包,判断为网络连接");
return true;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
if (ipProcess != null) {
ipProcess.destroy();
}
runtime.gc();
}
return false;
}
https://blog.csdn.net/yyanjun/article/details/81197991
参考
public class Ping extends AsyncTask<String, Boolean, Boolean> {
@Override
protected Boolean doInBackground(String... strings) {
try {
Process p = Runtime.getRuntime().exec("ping -c 1 -w 3 " + strings[0]);
InputStream input = p.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
br.close();
isr.close();
input.close();
br.close();
Logs.i("返回的数据:"+builder+" 对比:"+builder.toString().contains("ttl"));
/*如果Ip地址Ping成功后数据里面会有ttl这个数据,所以对比这个字符串即可*/
return builder.toString().contains("ttl");
} catch (MalformedURLException e) {
Logs.e(e.toString());
return false;
} catch (IOException e) {
Logs.e(e.toString());
return false;
}
}
@Override
protected void onPostExecute(Boolean isPing) {
Logs.v("Ping的结果:" + isPing);
if(isPing){
/*设备Ip地址ping成功后向后台发送数据*/
if (!TextUtils.isEmpty(cllx)) {
if (INSPECT_START.equals(cllx)) {
//查验开始
inspectStart();
} else if (INSPECT_END.equals(cllx)) {
//查验结束
inspectEnd();
}
}
// DialogNoticeUtil.show(RequestAction.this,"执法记录仪连接成功");
}else {
DialogNoticeUtil.show(RequestAction.this,"执法记录仪连接失败");
}
}
}
————————————————
版权声明:本文为CSDN博主「ChampionDragon」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xxdw1992/article/details/103582908