Android - restore last viewed Activity

后端 未结 3 1495
深忆病人
深忆病人 2020-12-09 20:40

I have 3 different Activities that user navigates between in no particular order. My goal it twofold:

  1. When user switches to something else when app is resumed
3条回答
  •  醉酒成梦
    2020-12-09 20:53

    If your app hasn't been "terminated" then #1 should already work and #2 just requires saving any values that aren't managed automagically into the Bundle in onSaveInstanceState() then restoring them in onRestoreInstanceState().

    This is kind of a hack, but I think your best option for #1 in the case of the app actually being terminated would be to save the most recent Activity in the onResume of each of your Activity classes then when you first run the onCreate of your first activity do a check then start the correct Activity... maybe even put in a blank Activity at the beginning. Something like this:

    StartActivity:

    public class StartActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // get last open Activity
            String lastActivity = PreferenceManager.getDefaultSharedPreferences(this).getString("last_activity", "");
            if (last_activity == MyActivity2.getSimpleName()) {
                startActivityForResult(new Intent(this, MyActivity2.class));
            } else if (last_activity == MyActivity3.getSimpleName()) {
                startActivityForResult(new Intent(this, MyActivity3.class));
            } else {
                // assume default activity
                startActivityForResult(new Intent(this, MyActivity1.class));
            }
        }
    
        public void onActivityResult() {
            // kill the activity if they go "back" to here
            finish();
        }
    }
    

    Then in all the other Activities (MyActivity1,2,3) save the values like so:

    @Override
    public void onResume() {
        Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
        e.putString("last_activity", getClass().getSimpleName());
        e.commit();
    
        super.onResume();
    }
    

    You'll also have to handle saving /restoring the data for each Activity manually. You could save all the values you need into the preferences inside the onPause() of each of the Activities then restore it in the onResume().

提交回复
热议问题