android监听wifi状态广播
时间: 2023-07-22 17:27:39 浏览: 123
在 Android 中,你可以通过注册广播接收器来监听 WiFi 状态的变化。
以下是一个监听 WiFi 状态变化的广播接收器示例:
```
public class WifiStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
// WiFi 已启用
break;
case WifiManager.WIFI_STATE_DISABLED:
// WiFi 已禁用
break;
}
}
}
}
```
在你的 Activity 中,你需要注册这个广播接收器:
```
private WifiStateReceiver wifiStateReceiver;
@Override
protected void onResume() {
super.onResume();
wifiStateReceiver = new WifiStateReceiver();
IntentFilter intentFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(wifiStateReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiStateReceiver);
}
```
这样,当 WiFi 的状态发生变化时,`WifiStateReceiver` 就会收到广播。
阅读全文