Android 网络链接状态 网络是否可用

判断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;
    }

你可能感兴趣的:(Android,Http)