Android 網路連結狀態 網路是否可用
阿新 • • 發佈:2019-01-10
判斷Android 網路已連線狀態下,網路是否可用。
首先分析是否連結網路;
在根據Android版本判斷網路是否可用:6.0以後系統提供API可用,6.0之前使用ping命令即可。
public static boolean netCanUse(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { if (!mNetworkInfo.isAvailable()) { return false; } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork()); return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); } else { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("ping -c 3 www.baidu.com"); int exitValue = ipProcess.waitFor(); Log.i("Avalible", "Process:" + exitValue); return (exitValue == 0); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } } return false; }