2009-12-07

[Android] Toggle airplane mode

Toggling airplane mode in Android is easy. First, you tell it you want to turn it on/off by two steps

  1. Set an integer in System.Settings for others to query,
    Settings.System.putInt(Settings.System.AIRPLANE_MODE_ON, 1 /* 1 or 0 */);
  2. Broadcast an Intent object,
    Intent i = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    i.putExtra("state", toggle); // toggle is an boolean primitive.
    context.sendBroadcast(i);

Don't know why Android SDK doesn't do the first step for me when System receives the Intent object. The sad thing is that there isn't many one-stop-shopping experiences in Android programming.

Second, you check if the telephony system has accepted your request by setting up a listener listening to SERVICE_STATE.

telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(
    new PhoneStateListener() {
        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            int state = serviceState.getState();

            // Do whatever you want for current state. Possible values:
            // ServiceState.STATE_POWER_OFF,
            // ServiceState.STATE_IN_SERVICE,
            // ...
        }
    },
    PhoneStateListener.LISTEN_SERVICE_STATE);