Sunday, April 19, 2009

Android: Controlling Airplane Mode

I've spent a lot of time looking for how to programatically enable and disable Airplane Mode. It doesn't appear that the 1.1 Android SDK exposes it yet.

Here're some code snippets to help with that.

Check to see if it is enabled or not:

boolean isEnabled = Settings.System.getInt(
Settings.System.AIRPLANE_MODE_ON, 0) == 1;

To toggle it:

// toggle airplane mode
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);

To get notifications on state change:

IntentFilter intentFilter = new IntentFilter("android.intent.action.SERVICE_STATE");

BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.d("AirplaneMode", "Service state changed");

context.registerReceiver(receiver, intentFilter);

Please share if there's an easier way!