工具-网络 Posted on 2022-03-16 | In Android代码片段 Android 使用ping判断网络/WIFI连接是否可用 12345678910111213141516171819202122232425262728293031323334353637383940414243/** * 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;}