如何防止自动连接到WiFi

时间:2012-07-25 06:54:04

标签: java android android-networking

我从通知栏打开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方法中取消注册。

BroadcastReceiver代码:

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); 
            }
        }
    }
}

}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

尝试禁用Wifi .............和需要时启用 .........

boolean isOn = false;
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(isOn);