网络监听状态判断

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);
}

你可能感兴趣的:(网络监听状态判断)