How to programatically turn on wifi when aeroplane(airplane) mode is on in Android?

瘦欲@ 提交于 2021-02-11 15:28:16

问题


I am developing a wifi search application. Whenever the device is in aeroplane mode wifi is turned off automatically. I found that system apps can turn on the wifi even if the device is in aeroplane mode. I am testing it on Android 9. How do I make my app can able to turn on the wifi?


回答1:


In android 9, you cannot turn on wifi programmatically when the device is in airplane mode or is tethering hotspot. In this case, the

boolean retVal = mWifiManager.setWifiEnabled(true);

always returns false as the device is in airplane mode. But I've found an unethical way to do it. Not sure even if is it good to do it this way. Works for me.

if(myWifiManager.isWifiEnabled()){
        System.out.println("Toggle Wifi Enabled going to disable");
        myWifiManager.setWifiEnabled(false);
    }
    else{
        System.out.println("Wifi Disabled going to enable ");
        if(Settings.System.getInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0) != 0){
             Runtime.getRuntime().exec("adb shell settings put global airplane_mode_radios cell,nfc,wimax,bluetooth");
        }
        myWifiManager.setWifiEnabled(true);
        System.out.println("WI: "+myWifiManager.isWifiEnabled());
    }

Explanation for the adb command is here. As mentioned in the link, you can turn things back to how they were by adding the following code when the airplane mode is switched off.

Runtime.getRuntime().exec("adb shell settings delete global airplane_mode_radios");



来源:https://stackoverflow.com/questions/54321635/how-to-programatically-turn-on-wifi-when-aeroplaneairplane-mode-is-on-in-andro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!