I want to turn airplane mode on and off with the help of a button. How can I turn airplane mode on and off in Android?
manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
mainactivity:
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
updateUI(isAirPlaneMode());
}
public void flightToggle(View view) {
boolean state = isAirPlaneMode();
toggleAirPlaneMode(state);
updateUI(!state);
Toast.makeText(this, state + "", Toast.LENGTH_SHORT).show();
}
public void toggleAirPlaneMode(boolean state) {
Settings.System.putInt(this.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, state ? 0 : 1);
}
public void updateUI(boolean state){
if (state){
button.setText(TURN_OFF);
} else {
button.setText(TURN_ON);
}
}
public boolean isAirPlaneMode(){
return Settings.System.getInt(this.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
}