美文网首页简化开发
网络监听状态判断

网络监听状态判断

作者: Android14k纯金大佬 | 来源:发表于2022-03-24 14:01 被阅读0次

    Android10(API级别29)之前

    ConnectivityManager cm =         
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
                              activeNetwork.isConnectedOrConnecting();
    

    Android10之后已经弃用,改用 NetworkCallbacks

    1,新建一个NetworkCallbackImpl类继ConnectivityManager.NetworkCallback

    public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            Log.i(TAG, "网络已连接 ");
        }
     
        @Override
        public void onLost(Network network) {
            super.onLost(network);
            Log.i(TAG, "网络已断开");
        }
     
        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    Log.i(TAG, "wifi已经连接");
                } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    Log.i(TAG, "数据流量已经连接");
                } else {
                    Log.i(TAG, "其他网络");
                }
            }
        }
    }
    

    2,注册实现类NetworkCallbackImpl

     NetworkCallbackImpl networkCallback = new NetworkCallbackImpl();
     NetworkRequest.Builder builder = new NetworkRequest.Builder();
     NetworkRequest request = builder.build();
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connMgr != null) {
       connMgr.registerNetworkCallback(request, networkCallback);
    }
    

    相关文章

      网友评论

        本文标题:网络监听状态判断

        本文链接:https://www.haomeiwen.com/subject/cjgkjrtx.html