从通知栏打开 WiFi 适配器后,我尝试阻止自动连接到 WiFi 并显示对话框。
我以编程方式注册了接收 WIFI_STATE_CHANGED_ACTION 的 BroadcastReceiver。在 WIFI_STATE_ENABLED 我从配置的网络列表中删除网络。但它不起作用。
我在以下位置注册 BroadcastReceiver:
@Override
protected void onStart() {
super.onStart();
registerReceiver(wifiStatusReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
并在 onStop 方法中注销。
广播接收器代码:
public class WiFiStatusReceiver extends BroadcastReceiver {
private WifiManager wifiManager;
@Override
public void onReceive(Context context, Intent intent) {
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if(!isInitialStickyBroadcast()) { //it is not a sticky intent
switch(wifiManager.getWifiState()) {
case WifiManager.WIFI_STATE_ENABLING:
Toast.makeText(context, R.string.enabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_ENABLED:
Toast.makeText(context, R.string.enabled_wifi, Toast.LENGTH_SHORT).show();
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
break;
case WifiManager.WIFI_STATE_DISABLING:
Toast.makeText(context, R.string.disabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_DISABLED:
Toast.makeText(context, R.string.disabled_wifi, Toast.LENGTH_SHORT).show();
break;
}
} else { //is a sticky intent
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
}
}
}
有什么建议么 ?