androidmodeairplane-mode

Toggle airplane mode in Android


Did I make a mistake? It's not working.

public void airplane() {
    boolean isEnabled = Settings.System.getInt(this.getApplicationContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    Settings.System.putInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
    //Settings.System.putInt(this.getApplicationContext().getContentResolver(),Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
}

Solution

  • This answer contains code necessary to do this. Also make sure you have the WRITE_SETTINGS permission.

    Adapted from Controlling Airplane Mode:

    // read the airplane mode setting
    boolean isEnabled = Settings.System.getInt(
          getContentResolver(), 
          Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    
    // toggle airplane mode
    Settings.System.putInt(
          getContentResolver(),
          Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);
    
    // Post an intent to reload
    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", !isEnabled);
    sendBroadcast(intent);