androidandroid-intentairplane-mode

Enable and Disable Airplane Mode successively Android


I am just a starter in Android. I have an Android code which has a Button. On click of the button, it should Invoke AirPlane mode and then again back to normal mode. Here is my code :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // load controls
    tvStatus = (TextView)findViewById(R.id.tvStatus);
    togState = (Button)findViewById(R.id.togState);

    // 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);

                            state = isAirplaneMode();
                            // toggle the state
                            toggleAirplaneMode(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 boolean isAirplaneMode() {
    return Settings.System.getInt(this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
}

}

The problem here is, my phone will go in AirPlane mode and it toggles back also. But this process I cannot stop. Is the problem with the way I handled the OnClick Listener by calling same method (toggleAirplaneMode) twice?

Regards,


Solution

  • I got it finally

    I used this in my code

                public void onClick(View v) {
                    // check current state first
                    boolean state = isAirplaneMode();
                    // toggle the state
                    toggleAirplaneMode(state);
    
                   state = isAirplaneMode();
                    // toggle the state
                    toggleAirplaneMode(state);
                    ser = new ServiceState();
                    ser.setState(STATE_IN_SERVICE);
                   }
    

    And I have declared final int STATE_IN_SERVICE = 0; before OnCreate. And ser is the instance of ServiceState.

    Thank you for your replies.