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>
<activity android:name=".GameActivity"
    android:launchMode="singleTask">
</activity>

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");
        onBackPressed();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

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

(from http://stackoverflow.com/a/3142471)

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

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

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

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

 

 

Reference:

The Cheese Factory. (2015). Understand Android Activity’s launchMode: standard, singleTop, singleTask and singleInstance . https://inthecheesefactory.com/blog/understand-android-activity-launchmode/en