Controlling Airplane Mode
Just having fun with some system settings, specifically, Airplane Mode.
So what I’m going to do is to create an application that does switch/toggle the Airplane Mode on the phone.
Using a TextView to display the current state of Airplane Mode, and a ToggleButton to switch/toggle the current mode.
This is how it’s done:
package pete.android.study;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class Main extends Activity {
// constants
static final String STATUS_ON = "Airplane Mode: ON";
static final String STATUS_OFF = "Airplane Mode: OFF";
static final String TURN_ON = "Turn ON";
static final String TURN_OFF = "Turn OFF";
// controls
TextView tvStatus;
ToggleButton togState;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// load controls
tvStatus = (TextView)findViewById(R.id.tvStatus);
togState = (ToggleButton)findViewById(R.id.togState);
// update UI at first time loading
updateUI(isAirplaneMode());
// set click event for button
togState.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// check current state first
boolean state = isAirplaneMode();
// toggle the state
toggleAirplaneMode(state);
// update UI to new state
updateUI(!state);
}
});
}
public void toggleAirplaneMode(boolean state) {
// toggle airplane mode
Settings.System.putInt(this.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, state ? 0 : 1);
// broadcast an intent to inform
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !state);
sendBroadcast(intent);
}
public void updateUI(boolean state) {
if(state) {
tvStatus.setText(STATUS_ON);
togState.setText(TURN_OFF);
} else {
tvStatus.setText(STATUS_OFF);
togState.setText(TURN_ON);
}
}
public boolean isAirplaneMode() {
return Settings.System.getInt(this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
}
}
Pretty much easy to understand, comments do the explanation itself. Guess you have it!
Just a note: the “sendBroadcast()” will notify the system about settings/config changed; hence, you can see the top icon on the status bar (the ‘Airplane‘ icon) update as you switch between the modes.
Browse Source Code from Android-Newbie Repository
Cheers,
Pete Houston



You forget to say about manifest file: add android.permission.WRITE_SETTINGS
@Steven: I’ve updated repository for source code. Check it out!
Hi, Pete.
Thanks a lot.
Hi, Pete,
I am interested how it’s done,
but can’t see the code on the website.
Can you send this project for reference ?
Many thanks.
My email:aeioutop@yahoo.com.tw