Android - restore last viewed Activity

Bostone picture Bostone · Sep 20, 2009 · Viewed 20.3k times · Source

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 I want to start where user left even if app was terminated
  2. When last activity is resumed I want to restore it to the last viewed state (this one I think I have a pretty good idea on how to achive)

I think the problem is not start/stop - where I pretty much get what I need, but onCreate() if app was terminated. In that case - it picks Activity that I configured in the manifest. I suppose I can put something in onCreate() method of that default activity but is there a better way that I'm maybe missing?

Answer

Jeremy Logan picture Jeremy Logan · Sep 20, 2009

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().