How to return to the latest launched activity when re-launching application after pressing HOME?

sole picture sole · Jun 14, 2011 · Viewed 27.2k times · Source

Familiar scenario: I have a Main activity that launches a Game activity when a button is pressed. If the user presses HOME, and then launches my application again, it should be presented with the Game activity, which is what he was doing last when using the application.

However, what happens instead is he gets the Main activity again. I have the feeling that Android is creating another instance of MainActivity and adding it to the stack for that application, instead of just picking whatever was on the top, because if I press BACK after relaunching the app, I get to the Game activity! And the Main.onCreate method is called every time, instead of calling GameActivity.onResume.

My AndroidManifest.xml is pretty much 'bare bones':

<activity android:name="MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name="GameActivity" android:label="@string/app_name">
</activity>

As you can see, nothing too fancy.

And this is how the new activity is launched, very simple too:

Intent intent = new Intent(this, GameActivity.class);
startActivity(intent);

In theory this should work in Android just "out of the box", as the answer to a very similar question says: Maintaining standard application Activity back stack state in Android (using singleTask launch mode), but it isn't.

I've been reading and re-reading the documentation on Activity and Task and Stacks and browsing all related answers in SO but I can't understand why such a simple setup is not quite working as expected.

Answer

Sachin Gurnani picture Sachin Gurnani · May 15, 2012
    @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
        // Activity was brought to front and not created, 
        // Thus finishing this will get us to the last viewed activity 
        finish(); 
        return; 
    } 

    // Regular activity creation code... 
}