android 代码怎么实时监控连接当前wifi热点的设备的连接或断开事件?
android 代码怎么实时监控连接当前wifi热点的设备的连接或断开事件?
问题描述
android 代码怎么实时监控连接当前wifi热点的设备的连接或断开事件?
如题,手机A开了热点,手机B打开Wifi连接上了A。那么当B关闭Wifi按钮时,A怎么实时感知到。有没有实现的代码、方法。
解决方案
// 当网络变化的时候系统会发出一个广播 Broadcast,只要在程序中注册一个广播接收器 BroadcastReceiver,并在 IntentFilter 中添加相应的过滤,这样一旦网络有变化,程序就能监听到
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private void registerDateTransReceiver() {
Log.i("Phone Link", "register receiver " + CONNECTIVITY_CHANGE_ACTION);
IntentFilter filter = new IntentFilter();
filter.addAction(CONNECTIVITY_CHANGE_ACTION);
filter.setPriority(1000);
registerReceiver(new MyReceiver(), filter);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Phone Link", "PfDataTransReceiver receive action " + action);
if(TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){ // 网络变化的时候会发送通知
Log.i("Phone Link", "网络变化了");
return;
}
}
// 当网络变化时,从有网到没网也会发广播,接收到广播的时候要判断当前网络是可用还是不可用状态
public static NetworkInfo getActiveNetwork(Context context){
if(context == null)
return null;
ConnectivityManager mConnMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(mConnMgr == null)
return null;
NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 获取活动网络连接信息
return aActiveInfo;
}
解决方案二:
Android监听网络变化
注册方式:
1.
Xml代码 收藏代码
android:name="包名.ConnectionChangeReceiver"
android:label="NetworkConnection" >
2.
Java代码 收藏代码
/*
手动注册网络状态变化,或在清单文件配置。
*/
private void registerNetStateReceiver() {
Log.i("--bxm register netstate receiver...");
mConnectivityReceiver = new ConnectionChangeReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnectivityReceiver, filter);
}
其中 ConnectionChangeReceiver类为:
Java代码 收藏代码
public class ConnectionChangeReceiver extends BroadcastReceiver {
private final static NetConnectionStateMgr dataStateMgr = NetConnectionStateMgr.getInstance();
@Override
public void onReceive(Context context, Intent intent) {
Log.i("--ConnectivityReceiver.onReceive()...");
String action = intent.getAction();
Log.i("--action=" + action);
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
Log.i("--Network Type = " + networkInfo.getTypeName());
Log.i("--Network State = " + networkInfo.getState());
if (networkInfo.isConnected()) {
Log.i("--bxm Network connected");
dataStateMgr.setDataState(NetConnectionStateMgr.DATA_CONNECTIONED);
}
} else {
Log.e("--bxm Network unavailable");
dataStateMgr.setDataState(NetConnectionStateMgr.DATA_CONNECTION_UNAVAILABLE);
}
dataStateMgr.notifyDataSetChanged();
}
}
上面的NetConnectionStateMgr是自己实现的观察者类,方便用而已。
注意权限配置:
解决方案三:
注意权限配置:
解决方案四:
注意权限配置:
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
下一篇: 比较常用的几个正则表达式匹配数字(收藏)