save the state when back button is pressed

徘徊边缘 提交于 2019-12-28 04:08:07

问题


I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used 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();
 }

回答1:


What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,

@Override
public void onBackPressed() {

    super.onBackPressed();
}

And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the 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();
}



回答2:


you can use this way

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

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

save your application state in this method.



来源:https://stackoverflow.com/questions/12171320/save-the-state-when-back-button-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!