Android Tasks and Back Stack
activity:launchMode in the AndroidManifest.xml

Every time I develop an Android app and handle back stack and switching between activities, I am confused with the using of activity attributes like launchMode, taskAffinity, allowTaskReparenting, etc,
and lots of intent flags like FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_SINGLE_TOP...
Today I am going to relearn all of them by code (we’ll never know what will happen until we really build it on devices even though we have already read the docs). Let’s get started!
Here is the sample app on Google play, you can learn it with the app.

Prerequisites
First, I strongly recommend you read the doc on Android Developer Understand Tasks and Back Stack, it will help us to understand how the back stack works.
activity:launchmode
This attribute should be added to AndroidManifest.xml
like below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.launchmode.example">
<application ...>
<activity
android:name=".launchmode.LaunchModeStandardActivity"
android:launchMode="standard" />
</application>
</manifest>
Four launch mode
android:launchMode=”standard”
Simplest activity launch behavior, create a new instance of the activity on the top of the target task.

android:launchMode=”singleTop”
- If the activity doesn’t exist, it will be created and put on the top of the task.
- If the activity exists but not on the top of the task, a new instance will be created and put on the top of the task.

3. If the activity is on the top of the task, it won’t create a new instance, but invoke top activity’s onNewIntent().

android:launchMode=”singleTask”
- If the activity doesn’t exist, it will be created and put on the top of the task.

2. If the activity exists, it won’t create a new instance, but invoke the existing activity’s onNewIntent()
and clear all activities above it.

android:launchMode=”singleInstance”
- If the activity doesn’t exist, a new task will be created and the activity will be the ONLY member of the task.
- If the other activities are created, they can’t be a member of the specific task.
- If the activity exists, it will go back to its own task and invoke
onNewIntent().

That’s all for the launch modes setting in AndroidManifest.xml. Hopefully, this article helps to clarify how to use them.
The next article will introduce Intent Flags
, stay tuned! 😃