1、新建一个类,使其继承BroadcastReceiver
public class NetWorkChangReceiver extends BroadcastReceiver {
private static final String TAG = "wen-------";
/**
* 获取连接类型
* @param type
* @return
*/
private String getConnectionType(int type) {
String connType = "";
if (type == ConnectivityManager.TYPE_MOBILE) {
connType = "4G网络数据";
} else if (type == ConnectivityManager.TYPE_WIFI) {
connType = "WIFI网络";
}
return connType;
}
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {// 监听wifi的打开与关闭,与wifi的连接无关
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
Log.e(TAG, "wifiState:" + wifiState);
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
}
}
// 监听网络连接,包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
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()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI ||
info.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.i(TAG, getConnectionType(info.getType()) + "连上");
}
} else {
Log.i(TAG, getConnectionType(info.getType()) + "断开");
}
}
}
}
2、静态注册,只需在AndroidManifest.xml中注册即可
<receiver android:name="com.wen.demo.receiver.NetWorkChangReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
3、动态注册,随着调用者的生命周期变化而变化,需在onDestroy()方法中取消注册。
private void regNetWork() {
netWorkChangReceiver = new NetWorkChangReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(netWorkChangReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (netWorkChangReceiver != null) {
unregisterReceiver(netWorkChangReceiver);
}
}
}