问题
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