How to make an android app return to the last open activity when relaunched?

The question:

Is it possible to configure an android app so that if a user has opened your app, launched numerous activities, then returns to the home screen and relaunches your app again, instead of going to the main activity they will instead be taken to the activity highest on the stack (the most recent activity in your app)?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

When launched via icon on the home screen, Android will always start the activity with the android.intent.action.MAIN filter in your AndroidManifest.xml, unless the application is already running (in which case it will obviously restore the activity on top of the stack).

To achieve what you described you can simply store the last visible activity in SharedPreferences and have a Dispatcher activity that starts the last activity according to the preferences.

So in every activity you want to re-start automatically:

protected void onPause() {

    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("lastActivity", getClass().getName());

And a Dispatcher activity similar to the following:

public class Dispatcher extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

        Class<?> activityClass;

        try {
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
            activityClass = Class.forName(
                prefs.getString("lastActivity", Activity1.class.getName()));
        } catch(ClassNotFoundException ex) {
            activityClass = Activity1.class;

        startActivity(new Intent(this, activityClass));


  • You could create a base class for the onPause override
  • The Dispatcher activity obviously needs to be the android.intent.action.MAIN action

Method 2

It’s not that complex. You just need to manipulate the manifest.



Read about the ‘android:exported’ & ‘android:alwaysRetainTaskState’ here:



Method 3

This is the default behaviour and this question has been asked several times before:
Android: keep task’s activity stack after restart from HOME
Android Run application from last Activity

Note that if you’re launching your application from Eclipse, that’s what breaks this default functionality. Changing your launch configuration to launch no activity should fix things.

However, as this behaviour was fixed in the 0.9.6 release of the ADT plugin for Eclipse in the past few weeks, you no longer need that workaround:

Applications launched from ADT now behave as if they were clicked from the Home screen.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment