Roger Ganga
Roger Ganga

Reputation: 11

How to enable/disable airplane mode?

I am trying enable/disable airplane mode programmatically but the following code is not working.The app stops unexpectedly while running and I have to forceclose

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_airplanemode);

Code to check the status of airplane mode boolean isEnabled = Settings.System.getInt( getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;

Code to toggle

    Settings.System.putInt(
              getContentResolver(),
              Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);

Reloading the intent

    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", !isEnabled);
    sendBroadcast(intent);
        TextView a = new TextView(this);
        a.setText("AIRPLANE MODE : "+isEnabled);
        setContentView(a);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_airplanemode, menu);
    return true;
}

Upvotes: 1

Views: 5327

Answers (2)

Rajeev N B
Rajeev N B

Reputation: 1363

Try to add required permissions to your Androidmanifest.xml file Try adding

android.permission.WRITE_SETTINGS

Upvotes: 0

Royston Pinto
Royston Pinto

Reputation: 6731

You need to do the following. Add the following to your Manifesf file

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

And use the following lines of code in your onResume(),

Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 1);
newIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
newIntent.putExtra("state", true);
sendBroadcast(newIntent);

This should work, do not need to add context.sendBroadcast().

Upvotes: 4

Related Questions