写一个类myReceiver继承BroadcastReceiver类
重写onReceiver()方法,onReceiver()方法默认在UI线程运行,可直接显示Toast
public void onReceive(Context context, Intent intent) {
//获得ConnectivityManager对象
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)
//获取ConnectivityManager对象对应的NetworkInfo对象
//获取WIFI连接的信息
NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//获取移动数据连接的信息
NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
Toast.makeText(context, "WIFI已连接,移动数据已连接", Toast.LENGTH_SHORT).show();
} else if (wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
Toast.makeText(context, "WIFI已连接,移动数据已断开", Toast.LENGTH_SHORT).show();
} else if (!wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
Toast.makeText(context, "WIFI已断开,移动数据已连接", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "WIFI已断开,移动数据已断开", Toast.LENGTH_SHORT).show();
}
在Activity中的onResume()方法中注册广播接收器
protected void onResume() {
super.onResume();
//注册广播接收器
if (myReceiver == null) {
myReceiver = new MyReceiver();
}
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myReceiver, filter);
}
在Activity中的onResume()方法中撤销广播接收器
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}