Save state when you press the back button

I am developing an Android application. If I press the back button, the state of my application must be saved. What should I use to save state. Confused by all of these onPause() , onResume() or onRestoresavedInstance() ??? which one should I use to save the state of my application? For example, when I press the exit button, my whole application should exit, did I use the finish ()?

  public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); s1=(Button)findViewById(R.id.sn1); s1.setOnClickListener(this); LoadPreferences(); s1.setEnabled(false); } public void SavePreferences() { SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("state", s1.isEnabled()); } public void LoadPreferences() { System.out.println("LoadPrefe"); SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); Boolean state = sharedPreferences.getBoolean("state", false); s1.setEnabled(state); } @Override public void onBackPressed() { System.out.println("backbutton"); SavePreferences(); super.onBackPressed(); } 
+7
source share
2 answers

What you need to do, instead of using KeyCode Back, you will override the method below in your activity

 @Override public void onBackPressed() { super.onBackPressed(); } 

And save the state of your button using SharedPrefrence , and the next time you enter your Activity, get the value from Sharedpreference and set the enabled state of your button accordingly.

Example,

 private void SavePreferences(){ SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("state", button.isEnabled()); editor.commit(); // I missed to save the data to preference here,. } private void LoadPreferences(){ SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); Boolean state = sharedPreferences.getBoolean("state", false); button.setEnabled(state); } @Override public void onBackPressed() { SavePreferences(); super.onBackPressed(); } onCreate(Bundle savedInstanceState) { //just a rough sketch of where you should load the data LoadPreferences(); } 
+8
source

you can use this method

 public void onBackPressed() { // Save settings here }; 

Called when an activity detects a keystroke from the back. The default implementation simply terminates the current activity, but you can override it to do whatever you want.

save application state in this method.

+3
source

All Articles