Skip to content Skip to sidebar Skip to footer

Android - Restore Last Viewed Activity

I have 3 different Activities that user navigates between in no particular order. My goal it twofold: When user switches to something else when app is resumed I want to start wher

Solution 1:

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:

publicclassStartActivityextendsActivity {
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // get last open ActivityString lastActivity = PreferenceManager.getDefaultSharedPreferences(this).getString("last_activity", "");
        if (last_activity == MyActivity2.getSimpleName()) {
            startActivityForResult(newIntent(this, MyActivity2.class));
        } elseif (last_activity == MyActivity3.getSimpleName()) {
            startActivityForResult(newIntent(this, MyActivity3.class));
        } else {
            // assume default activitystartActivityForResult(newIntent(this, MyActivity1.class));
        }
    }

    publicvoidonActivityResult() {
        // kill the activity if they go "back" to herefinish();
    }
}

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

@OverridepublicvoidonResume() {
    Editore= 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().

Solution 2:

Keep in mind that onSaveInstanceState() isn't workable for long-term state, i.e. the user powers the phone down and then turns it back on at an indeterminate point later. You will need to create your own long-term state mechanism if you wish for your state to survive power cycles.

Solution 3:

I believe you want to implement onSaveInstanceState and that will store your activities current state in a bundle. That bundle will be passed into your activity in onCreate, and you can use it to reset your values.

http://developer.android.com/guide/topics/fundamentals.html#actstate

Post a Comment for "Android - Restore Last Viewed Activity"