Search code examples
androidtaskretain

How to retain the task of the activity even when closing the app Android


I have a switch button in my android app I intend to switch it on but after I exit the app by removing it on my background task when I opened again the app it goes back to normal and switch goes back to off again. i=I want to retain or save the activity which I have been left. How am I going to retain the task of my activity basically the fragment itself? Am I going to use On pause?

@Override
public void onPause() {
    super.onPause();

}

Solution

  • You can accomplish this using shared preferences. For example, in onCreate, load the switch state from shared preferences (with a default for the first time)

    SharedPreferences prefs = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE);
    switchState = prefs.getBoolean("MyBoolean", false); // switchState being a boolean class member
    // then set the switch to switchState
    

    When the user updates the switch, change the stored value of switchState and in onPause save the updated state to the shared preferences

    @Override
    public void onPause() {
        super.onPause();
        SharedPreferences.Editor ed = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE).edit();
        ed.putBoolean("MyBoolean", switchState);
        ed.apply();
    }