androidmodeairplane-mode

Unable to turn off Airplane mode


I've create an app with a button that allows airplane mode to be toggled on and off. Works fine when turning airplane mode on. But strangely, airplane mode seems to stay on when it is toggled off.

If I check the phone settings after I turn it off, they indicate that airplane mode is off. But the airplane mode icon still shows in the top bar of the phone, and holding down the phone's power button shows that airplane mode is still on.

Not sure why the setting would show as off when it's still on?

Here is the code I'm using to turn it off - I've debugged and it's definitely hitting this. mContext is a variable I'm using to hold the context, this is passed into a settings class which then has methods in for turning airplane mode off and on:

System.putInt(mContext.getContentResolver(),
android.provider.Settings.System.AIRPLANE_MODE_ON, 0);
this.airplaneOn = false;
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", 0);
mContext.sendBroadcast(intent);

And here's the code I'm using to check the status of airplane mode -

public boolean isAirplaneOn() {
  int airplaneMode = 0;
  try {
    airplaneMode = System.getInt(mContext.getContentResolver(),
  android.provider.Settings.System.AIRPLANE_MODE_ON);
    } catch (SettingNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (airplaneMode == 1) {
        this.airplaneOn = true;
    } else {
        this.airplaneOn = false;
    }
    return airplaneOn;
}

In both cases, this.airplaneOn is a private boolean which stores the status of airplane mode.

Could I be doing something silly here, or is checking this setting somehow unreliable?


Solution

  • I've had success doing the following code:

    public static boolean isFlightModeEnabled(Context context) {
        return Settings.System.getInt(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    }
    
    public static void toggleFlightMode(Context context) {
        boolean isEnabled = isFlightModeEnabled(context);
    
        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);
    
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", !isEnabled);
        context.sendBroadcast(intent);
    }
    

    The only difference I see between my code and yours is that in your putInt() you have hard-coded 0.

    One other thing to be aware of is according to the docs, ACTION_AIRPLANE_MODE_CHANGED is

    This is a protected intent that can only be sent by the system.

    I haven't had issues with this in the past, but perhaps your device is newer and enforcing something that the older phones I've had success with don't enforce.