Android 网络状态判断

2023-12-22 14:27:58

1、获取网络信息,首先需要获取权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2.1我们通过ConnectivityManager可以获取状态,但是我们需要考虑到Android版本不同获取方式不同。

2.1.1hasCapability可以判断网络是否连接,常用参数如下:

?NetworkCapabilities.NET_CAPABILITY_INTERNET:判断是否连上网

NetworkCapabilities.NET_CAPABILITY_VALIDATED:判断当前是否能上网,但是发现小米11Android12添加证书后,一直是false
?

 private static boolean netWorkState(Context context) {
        if (context != null) {
            try {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                // 通过版本去判断
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    Network network = connectivityManager.getActiveNetwork();
                    //network 为空,则表示没有网络
                    if (network != null) {
                        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                        // NetworkCapabilities   为空,则表示没有网络
                        if (capabilities != null) {
                            //capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) 小米11,android 12系统这个值一直是false
                            return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
                        }
                    }
                } else {
                    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                    if (info != null) {
                        return info.isAvailable();
                    }
                }
                return false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

2.1.2hasCapability可以判断网络类型,常用参数如下:

NetworkCapabilities.TRANSPORT_WIFI:表示接入的是WIFI网络
NetworkCapabilities.TRANSPORT_CELLULAR:表示接入的是数据网络

 public static void networkType(NetworkCapabilities networkCapabilities) {
        if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            //当前在使用Mobile流量上网
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            //当前在使用WiFi上网
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) {
            //当前使用蓝牙上网
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
            //当前使用以太网上网
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
            当前使用VPN上网
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE)) {
            //表示此网络使用Wi-Fi感知传输
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_LOWPAN)) {
            //表示此网络使用LoWPAN传输
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_USB)) {
            //表示此网络使用USB传输
        } else {
            //未知
        }
    }

2.2异步通过registerDefaultNetworkCallback获取网络状态(华为手机,在使用过程,网络状态不准确)

 ConnectivityManager  connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            //注册 NetworkCallBack
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                connectivityManager.registerDefaultNetworkCallback(networkCallBack);
            }
        }

2.2.1networkCallBack

 private ConnectivityManager.NetworkCallback networkCallBack = new ConnectivityManager.NetworkCallback() {
        private static final String TAG = "TAG";

        @Override
        public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            if (NetworkUtils.netWorkState(getBaseContext())) {
                Log.i(TAG, "onCapabilitiesChanged ---> ====网络可正常上网===网络类型为: " + NetworkUtils.networkType(MainActivity.this));
            }
           
        }

        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);
            Log.i(TAG, "==网络连接成功,通知可以使用的时候调用====onAvailable===");
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            Log.i(TAG, "==当网络连接超时或网络请求达不到可用要求时调用====onUnavailable===");

        }

        @Override
        public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {
            super.onBlockedStatusChanged(network, blocked);
            Log.i(TAG, "==当访问指定的网络被阻止或解除阻塞时调用===onBlockedStatusChanged==");

        }

        @Override
        public void onLosing(@NonNull Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
            Log.i(TAG, "==当网络正在断开连接时调用===onLosing===");

        }

        @Override
        public void onLost(@NonNull Network network) {
            super.onLost(network);
            Log.i(TAG, "==当网络已断开连接时调用===onLost===");

        }


        @Override
        public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties);
            Log.i(TAG, "==当网络连接的属性被修改时调用===onLinkPropertiesChanged===");

        }

    };

2.3异步通过ping方式判断网络状态

try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec("ping -c 1 8.8.8.8");
            int waitFor = p.waitFor();
            return waitFor == 0;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
return false;

文章来源:https://blog.csdn.net/qq_21467035/article/details/135150964
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。