Recipe 4.6 Switching to Airplane Mode

Android Versions
Level 1 and above
Permissions
android.permission.WRITE_SETTINGS
Source Code Download from Wrox.com
AirplaneMode.zip

If you want to turn off all the wireless connectivity on an Android device, you can programmatically enable Airplane mode on the device. This recipe shows you how.

Solution

To enable Airplane mode, use the putInt() method from the Settings.System class and pass in an ContentResolver object, together with the AIRPLANE_MODE_ON constant, and a value indicating whether to turn Airplane mode on (1) or off (0). You then utilize the Intent object’s extras bundle by adding state and setting its value to either true (to turn on Airplane mode) or false (to turn off Airplane mode). Finally, you send a broadcast using the Intent object:

package net.learn2develop.airplanemode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    private void SetAirplaneMode(boolean enabled){
        //---toggle Airplane mode---
        Settings.System.putInt(
              getContentResolver(),
              Settings.System.AIRPLANE_MODE_ON, enabled ? 1 : 0);
        Intent i = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        i.putExtra("state", enabled);
        sendBroadcast(i);
    }    

}

To enable your application to turn on ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.