使用广播 监听WiFi连接状态
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
//RSSI信号强度变化
case WifiManager.RSSI_CHANGED_ACTION:
int rSSi = intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, -200);
int strength = WifiManager.calculateSignalLevel(rssi, Constants.MAX_WIFI_SIGNAL_STRENGTH);
//将WiFi信号强度传到controller层中updataWiFisingleStrenge方法中
mWifiSignalController.updatewifiSignalStrength(strength);
break;
default:
break;
}
}
对ConnectivityManager和WifiManager进行创建和callback注册
//Android的系统广播ConnectivityManager实现网络监听
mConnectivityManager = context.getSystemService(ConnectivityManager.class);
//要操作WIFI设备,需要先获取Context.getSystemService(Context.WIFI_SERVICE)来获取WifiManager对象,并通过这个对象来管理WIFI设备
mWifiManager = context.getSystemService(WifiManager.class);
mWifiSignalCallback = new WifiConnectionCallback(this);
mWifiSignalListener = new WifiSignalListener(this);
注册广播
IntentFilter wifiSiganlFilter = new IntentFilter();
wifiSiganlFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mContext.registerReceiver(mWifiSignalListener, wifiSiganlFilter);
NetworkRequest wifiRequest = new NetworkRequest.Builder().addCapability(
设置感兴趣的网络:计费网络
NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
mConnectivityManager.registerNetworkCallback(wifiRequest, mWifiSignalCallback);
判断WiFi是否连接
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
int networkId = wifiInfo.getNetworkId();
// int wifi = WifiInfo.getRssi();//获取wifi信号强度
mConnected = networkId != -1;
return networkId != -1;