singleTask launchMode in Android

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
singleTask launchMode in Android

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the singleTask launchMode in Android.

We use launchMode to give instructions to the Android operating system about how to launch the activity.

There are various types of launchMode in Android, but for this blog, we are focusing on singleTask.

singleTask launchMode

When we use launchMode="singleTask", the following cases are possible:

  • If an Activity does not exist in an already created Task, then it starts the new Activity in a new Task with the Activity's new instance at the root of that Task.
  • If an Activity exists in an already created Task, the Task is brought forward with the Activity's last state restored and this Activity receives the new intent through the onNewIntent() method.
  • Only one instance of the Activity can exist at a time.

Now, let's understand the above points with examples.

Assume we have the Activities as A, B, C, D, and E. And, we have added launchMode="singleTask" for Activity C.

Example 1

Let's say we have the state of the Activity Stack before launching Activity C as follows:

A > B

Here, we navigated from Activity A to Activity B. And now we want to navigate to Activity C from Activity B.

Keep this in mind that we have launchMode="singleTask" for Activity C.

Now, after the launch of Activity C from Activity B, the state of the Activity Stack will become as follows:

A > B > C

Here, Activity C gets launched as usual.

Example 2

Let's say we have the state of the Activity Stack before launching Activity C as follows:

A > B > C > D > E

Here, we navigated from Activity A to Activity B to Activity C to Activity D to Activity E. And now we want to navigate to Activity C from Activity E.

Keep this in mind that we have launchMode="singleTask" for Activity C.

Now, after the launch of Activity C from Activity E, the state of the Activity Stack will become as follows:

A > B > C

Two important things to note here:

  • Here, Activity C is the old instance only that gets the extras data through onNewIntent().
  • Activities D and E get destroyed.

Now, we have understood about the singleTask launchMode in Android.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.