Note: Press back button to return to Main Activity

Suppose we have two activities: MainActivity and GameActivity , and only MainActivity can start GameActivity.

Manifest setting:

<activity android:name=".MainActivity">
<activity android:name=".GameActivity"

From the Cheese Factory’ blog (2015), for an activity with “singleTask” as the launch mode:

But if there is an existed one, all of Activities placed above that singleTask Activity would be automatically and cruelly destroyed in the proper way (lifecycle trigged) to make that an Activity we want to appear on top of stack.

Overriding the onKeyDown() and onBackPressed() methods in GameActivity .

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        Log.d(log_name, "onKeyDown Called");
        return true;
    return super.onKeyDown(keyCode, event);

public void onBackPressed() {
    //Go back to main activity.
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);


Also, overriding the onKeyDown() and onBackPressed() methods in MainActivity, so that when the back button is pressed, home screen is returned.

public boolean onKeyDown(int keyCode, KeyEvent event) {
 //same as above...

public void onBackPressed() {

Overall Effect:

Start MainActivity (M), and then start GameActivity (G) from it.

–> Back stack: M > G (G is on the top of the stack).

Press back button in GameActivity.

–> Back stack: M > G > M (A new MainActivity is created).

If we start GameActivity again from MainActivity.

–> Back stack: M > G. (Since GameActivity is running, the newer MainActivity is destroyed).


Or if we Press back button in MainActivity, home screen is returned. And then we go back to the app.

–> Back stack: M > G > M (Remain unchanged).




The Cheese Factory. (2015). Understand Android Activity’s launchMode: standard, singleTop, singleTask and singleInstance .


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s