1.通过注册BroadCastReceiver进行网络监听。
1) 添加网络权限
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2)定义BroadCastReceiver
public class NetworkReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// 监听网络连接,包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听// 特殊注意:如果if条件生效,那么证明当前是有连接wifi或移动网络的,如果有业务逻辑最好把esle场景酌情考虑进去!if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {//获取联网状态的NetworkInfo对象NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);if (info != null) {//如果当前的网络连接成功并且网络连接可用if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {Log.e("nyz", getConnectionType(info.getType()) + "已连接");switch (info.getType()) {case ConnectivityManager.TYPE_WIFI:Log.e("nyz", "wifi网络" + "已连接");break;case ConnectivityManager.TYPE_MOBILE:Log.e("nyz", "数据网络" + "已连接");break;}} else {Log.e("nyz", getConnectionType(info.getType()) + "已断开");}} else {Log.e("nyz", "无网络");}}}/*** 获取连接类型** @param type* @return*/private String getConnectionType(int type) {String connType = "";if (type == ConnectivityManager.TYPE_MOBILE) {connType = "3-4G网络数据";} else if (type == ConnectivityManager.TYPE_WIFI) {connType = "WIFI网络";}return connType;}
}
需要注意的一点是 NetworkInfo 的两个方法:info.isConnected(); info.isAvailable();
info.isConnected(),不推荐使用 了,推荐的是通过NetWorkCallBack的方式。
通过这个方法判断网络是否可用是 return mState == State.CONNECTED;
判断的状态,和上面的Receiver中判断的方法是一样的。
/*** Indicates whether network connectivity exists and it is possible to establish* connections and pass data.* <p>Always call this before attempting to perform data transactions.* @return {@code true} if network connectivity exists, {@code false} otherwise.* @deprecated Apps should instead use the* {@link android.net.ConnectivityManager.NetworkCallback} API to* learn about connectivity changes. See* {@link ConnectivityManager#registerDefaultNetworkCallback} and* {@link ConnectivityManager#registerNetworkCallback}. These will* give a more accurate picture of the connectivity state of* the device and let apps react more easily and quickly to changes.*/@Deprecatedpublic boolean isConnected() {synchronized (this) {return mState == State.CONNECTED;}}
info.isAvailable(),从AndroidL开始总是返回true,所以用这个方法,不能准确判断,网络是否可用
/***Since Android L, this always returns {@code true}, because the system only* returns info for available networks. */
@Deprecatedpublic boolean isAvailable() {synchronized (this) {return mIsAvailable;}}
3)Activity中注册Receiver,在oDestroy中取消注册。
private void registerNetWorkReceiver() {//注册网络状态监听广播netWorkReceiver = new NetworkReceiver();IntentFilter filter = new IntentFilter();filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);registerReceiver(netWorkReceiver, filter);}@Overrideprotected void onDestroy() {super.onDestroy();if (netWorkReceiver != null) {unregisterReceiver(netWorkReceiver);}}
2.通过CallBack的方式监听网络:
1)定义NetworkCallbackImpl类,继承ConnectivityManager.NetworkCallback
class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {@Overridepublic void onAvailable(@NonNull Network network) {Log.e("nyz", "网络已连接");}@Overridepublic void onLost(@NonNull Network network) {super.onLost(network);Log.e("nyz", "网络已断开");}@Overridepublic void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {super.onCapabilitiesChanged(network, networkCapabilities);if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {Log.e("nyz", "wifi 网络");} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {Log.e("nyz", "蜂窝网络");} else {Log.e("nyz", "其他网络");}}}
2)注册CallBack:
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkRequest request = new NetworkRequest.Builder().build();networkCallback = new NetworkCallbackImpl();mConnMgr.requestNetwork(request, networkCallback);
3)反注册:
@Overrideprotected void onDestroy() {super.onDestroy();mConnMgr.unregisterNetworkCallback(networkCallback);}
3.其他判断网络是否可用的方法:
@SuppressLint("MissingPermission")public static boolean isNetworkAvailable(Context context) {ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (connMgr == null) {return false;}NetworkInfo[] infos = connMgr.getAllNetworkInfo();if (infos != null) {for (NetworkInfo info : infos) {if (info.getState() == NetworkInfo.State.CONNECTED) {return true;}}}return false;}
public static boolean isNetConnected(Context context) {if (context != null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();if (mNetworkInfo != null) {return mNetworkInfo.isConnected();}}return false;}