Android(安卓)NetworkCallback

Android API28对于网络状态的改变更倾向使用NetworkCallback

底下是一段对于过时方法的官方描述

getState()

This method was deprecated in API level 28. Apps should instead use theConnectivityManager.NetworkCallback API to learn about connectivity changes.ConnectivityManager.registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback) andConnectivityManager.registerNetworkCallback(NetworkRequest, PendingIntent). These will give a more accurate picture of the connectivity state of the device and let apps react more easily and quickly to changes.

 

ConnectivityManager.NetworkCallbackadded 

Base class for NetworkRequest callbacks. Used for notifications about network changes. Should be extended by applications wanting notifications. 

示例代码

        ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback(){                @Override                public void onAvailable(Network network) {                    super.onAvailable(network);                    Log.i(TAG, "onAvailable: "+network);                }                @Override                public void onLosing(Network network, int maxMsToLive) {                    super.onLosing(network, maxMsToLive);                    Log.i(TAG, "onLosing: "+network);                }                @Override                public void onLost(Network network) {                    super.onLost(network);                    Log.i(TAG, "onLost: "+network);                }                @Override                public void onUnavailable() {                    super.onUnavailable();                    Log.i(TAG, "onUnavailable: ");                }                @Override                public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {                    super.onCapabilitiesChanged(network, networkCapabilities);                    Log.i(TAG, "onCapabilitiesChanged: "+network);                }                @Override                public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {                    super.onLinkPropertiesChanged(network, linkProperties);                    Log.i(TAG, "onLinkPropertiesChanged: "+network);                }            });        }

Public methods

void onAvailable(Network network)

Called when the framework connects and has declared a new network ready for use.

void onCapabilitiesChanged(Network network, NetworkCapabilitiesnetworkCapabilities)

Called when the network the framework connected to for this request changes capabilities but still satisfies the stated need.

void onLinkPropertiesChanged(Network network, LinkProperties linkProperties)

Called when the network the framework connected to for this request changes LinkProperties.

void onLosing(Network network, int maxMsToLive)

Called when the network is about to be disconnected.

void onLost(Network network)

Called when the framework has a hard loss of the network or when the graceful failure ends.

void onUnavailable()

Called if no network is found in the timeout time specified inConnectivityManager.requestNetwork(NetworkRequest, NetworkCallback, int)call.

从上到下分别是:

网络连接时调用

网络功能更改但任满足需求时调用

网络连接属性修改时调用

网络即将断开时调用

网络断开时调用

网络缺失network时调用

 

registerDefaultNetworkCallback

added in API level 26

ConnectivityManager.NetworkCallback

added in API level 21

所以要针对高版本和低版本做差异化

 

网络是否连接

    public  boolean isNetworkAvailable(Context context) {        ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo[] infos = mgr.getAllNetworkInfo();        if (infos != null) {            for (int i = 0; i < infos.length; i++) {                if (infos[i].isConnected() == true) {                    return true;                }            }        }        return false;    }

WiFi是否连接

    public static boolean isWifiConnected(Context context) {        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);        if (mWiFiNetworkInfo != null) {            return mWiFiNetworkInfo.isConnected();        }        return false;    }

移动网络是否连接

    public static boolean isMobleConnected(Context context) {        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo mMobleNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);        if (mMobleNetworkInfo != null) {            return mMobleNetworkInfo.isConnected();        }        return false;    }

获取当前连接网络类型

    public void  getType(Context context) {        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();        if (networkInfo!=null){            Log.i(TAG, "yyy-type: "+networkInfo.isAvailable()+" "+networkInfo.isConnected()+" "+networkInfo.toString());            Log.i(TAG, "yyy-type: "+networkInfo.getSubtypeName()+" "+networkInfo.getTypeName()+" "+networkInfo.getExtraInfo());        }    }