Tasks and the back stack

How Android groups activities into tasks, how the back stack is built and popped, and how launch modes and intent flags change that behaviour. About 22 minutes.

Why it matters

  • The back stack decides what the user sees after pressing Back. A wrong mode or flag means lost navigation state, duplicate screens, or Back leaving the app too early.
  • Launch modes and flags are a common cause of "my Activity opened in the wrong place" bugs in production.
  • Interviewers often ask about launch modes, CLEAR_TOP, and NEW_TASK, and expect precise answers.
  • Modern back handling with OnBackPressedDispatcher and predictive back is a frequent senior-level topic.

The simple explanation

  • A task is a pile of sticky notes on a desk: the top note is the screen you see.
  • Pressing Back peels off the top note.
  • standard mode: always write a new note and put it on top.
  • singleTop: if the top note already says "Detail", reuse it with the new request instead of adding a new one.
  • singleTask: if "Detail" is anywhere in its pile, peel off everything above it so it becomes the top.
  • FLAG_ACTIVITY_NEW_TASK: put the note on the pile it belongs to (by affinity), starting a new pile only if that pile does not exist yet.

A task is a stack of activities the user sees as one job, shown as one entry in Recents. The back stack is that stack: the top activity is visible, and pressing Back finishes it and shows the one below. The system owns the stack; your app only asks for changes through launch modes and flags.

Each activity can declare a launchMode in the manifest. It controls what happens when an Intent targets that activity:

ModeBehaviour
standard (default)New instance, pushed on top
singleTopIf an instance is already on top, reuse it and call onNewIntent; otherwise a new instance
singleTaskAt most one instance. If it exists, its task comes forward, everything above it is finished, and it gets onNewIntent
singleInstanceLike singleTask, but it is the only activity in its task

singleInstancePerTask (Android 12+) allows one instance per task, at the root of that task.

Flags on the Intent change a single launch:

  • FLAG_ACTIVITY_NEW_TASK: start the activity in the task that matches its taskAffinity, creating that task if needed. Required when the caller is not an Activity (a Service, a BroadcastReceiver, the Application). Within your own app, with the default affinity, it usually lands in your existing task.
  • FLAG_ACTIVITY_CLEAR_TOP: if the target is already in the task, finish every activity above it. A standard target is itself finished and recreated, unless you also add SINGLE_TOP.
  • FLAG_ACTIVITY_SINGLE_TOP: if the target is already on top, reuse it (like singleTop, for this launch only).
  • FLAG_ACTIVITY_CLEAR_TASK: used together with NEW_TASK, it finishes every activity in the target task before the new one starts. The classic use is sending the user to the login screen after logout.

Back is handled by OnBackPressedDispatcher (or BackHandler in Compose). Overriding onBackPressed() is deprecated since API 33. Each callback can be tied to a LifecycleOwner, so a Fragment can register its own handler with viewLifecycleOwner without touching the Activity.

android:taskAffinity names the task an activity prefers. The default is the application's package name, so all your activities share one affinity. Affinity only matters when the activity is started with NEW_TASK, is singleTask or singleInstance, or uses allowTaskReparenting.

Try the simulator below: open screens A, B, C, press Back, and launch a screen as standard, singleTop, or singleTask to watch the stack change. It models one task in one app, and lets you pick the mode for each launch so you can compare them. In a real app the mode belongs to the activity in the manifest, so a singleTask activity never has two instances.

Try it: what is on the stack?

Pick how the next screen is launched, then open screens and press Back.

The task, top first
  1. Screen Avisible
What the system did
  1. Nothing yet. Open a screen.

Model: one task, all screens in the same app. singleTask is shown for an Activity that already lives in this task.

Notes

  • A task is a stack of activities, shown as one entry in Recents. The system owns it, not your app.
  • standard is the default launch mode: a new instance is created and pushed on top every time.
  • singleTop reuses the instance only if it is on top, and calls onNewIntent() instead of onCreate(). If it is lower in the stack, a new instance is created.
  • singleTask keeps at most one instance. Reusing it finishes every activity above it in its task.
  • singleInstance keeps one instance alone in its own task. It is rarely needed in modern apps.
  • In onNewIntent(), call setIntent(intent) if later code reads intent, otherwise intent still returns the old one.
  • FLAG_ACTIVITY_NEW_TASK is mandatory when starting an Activity from a Service, BroadcastReceiver, or the Application context. Since Android 10, starts from the background are also restricted; use a notification instead.
  • FLAG_ACTIVITY_CLEAR_TOP alone finishes and recreates a standard target; add SINGLE_TOP to keep the existing instance.
  • FLAG_ACTIVITY_CLEAR_TASK only works together with FLAG_ACTIVITY_NEW_TASK.
  • Since Android 12, pressing Back on the root launcher activity moves the task to the background instead of finishing the activity.
  • Overriding onBackPressed() is deprecated. Use OnBackPressedDispatcher.addCallback() (Views) or BackHandler (Compose). With predictive back enabled, onBackPressed() is not called at all.
  • Setting taskAffinity to another app's package name lets your activity join that app's task, a known task-hijacking risk. Leave the default unless you need a separate task.

Code example

This Activity shows three common launch patterns and a back callback. DetailActivity and LoginActivity use the default standard mode.

class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // 1. Standard: a new DetailActivity is pushed on top every time
        findViewById<Button>(R.id.btnStandard).setOnClickListener {
            startActivity(Intent(this, DetailActivity::class.java))
        }
 
        // 2. Reuse DetailActivity if it is in the task; finish everything above it
        findViewById<Button>(R.id.btnReuse).setOnClickListener {
            val intent = Intent(this, DetailActivity::class.java).addFlags(
                Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            )
            startActivity(intent)
        }
 
        // 3. Logout: wipe the task and make LoginActivity its only screen
        findViewById<Button>(R.id.btnLogout).setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java).addFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            )
            startActivity(intent)
        }
 
        // 4. Back handling: this callback runs instead of the default while it is enabled
        val confirmExit = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // e.g. close a panel first; then let the next handler run
                isEnabled = false
                onBackPressedDispatcher.onBackPressed()
            }
        }
        onBackPressedDispatcher.addCallback(this, confirmExit)
    }
}
  • CLEAR_TOP or SINGLE_TOP keeps the existing DetailActivity and delivers the intent to onNewIntent; CLEAR_TOP alone would finish and recreate it.
  • NEW_TASK or CLEAR_TASK finishes every activity in the task, so Back from LoginActivity cannot return to signed-in screens.
  • addCallback(this, ...) removes the callback automatically when the Activity is destroyed; in a Fragment pass viewLifecycleOwner.
  • For predictive back, keep the callback's isEnabled up to date ahead of time instead of deciding inside handleOnBackPressed, because the system must know before the gesture starts whether your app will handle it.

Run the idea in plain Kotlin

class TaskStack {
  private val stack = mutableListOf<String>()

  fun launch(name: String, mode: String = "standard") {
      when (mode) {
          "singleTop" -> {
              // Reuse only if it is already on top (Android calls onNewIntent).
              if (stack.lastOrNull() != name) stack.add(name)
          }
          "singleTask" -> {
              val idx = stack.indexOf(name)
              if (idx >= 0) {
                  // Finish everything above the existing instance.
                  while (stack.lastIndex > idx) stack.removeAt(stack.lastIndex)
              } else {
                  stack.add(name)
              }
          }
          else -> stack.add(name)
      }
  }

  fun back(): String? = if (stack.isEmpty()) null else stack.removeAt(stack.lastIndex)

  fun describe(): String = if (stack.isEmpty()) "(empty)" else stack.joinToString(" -> ")
}

fun main() {
  val task = TaskStack()

  task.launch("A")
  task.launch("B")
  task.launch("C")
  println("After A, B, C: " + task.describe())

  task.launch("B", "singleTask")
  println("After singleTask B: " + task.describe())

  task.launch("B", "singleTop")
  println("After singleTop B (no change): " + task.describe())

  task.launch("D")
  println("After standard D: " + task.describe())

  println("Back finishes " + task.back() + " | Stack: " + task.describe())
  println("Back finishes " + task.back() + " | Stack: " + task.describe())
}

Expected output: A -> B -> C, then A -> B (C is finished), then A -> B again, then A -> B -> D, then Back finishes D and then B, leaving A.

In production

Back from a notification leaves the app
  • A notification opened OrderDetailActivity directly through a PendingIntent.
  • When the app was not running, users tapped the notification, read the order, pressed Back, and landed on the home screen instead of the order list.
  • The new task contained only OrderDetailActivity, so there was nothing below it to go back to.
The fix
  • Declared android:parentActivityName=".OrderListActivity" and built the PendingIntent with TaskStackBuilder (addNextIntentWithParentStack, then getPendingIntent with FLAG_IMMUTABLE), so the task starts as order list, then detail.
  • In the single-Activity part of the app, used Navigation's deep links, which build the parent destinations for you.
  • Added a manual test for both cases: app killed, and app already open on another screen.
singleTask activity wipes navigation history
  • The app's main Activity was declared singleTask and also handled deep links.
  • When a user tapped a deep link while a multi-step form (separate activities) was open above it, every activity above the main Activity was finished.
  • Users lost their place in the form.
The fix
  • Changed the main Activity back to standard (or singleTop where repeated intents should reuse the top instance).
  • Used FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP only on the specific launches that should return to the main screen.
  • Added a test that opens the form, fires the deep link with adb shell am start, and checks the form is still in the task with adb shell dumpsys activity activities.

Common mistakes

  • Starting an Activity from a Service without FLAG_ACTIVITY_NEW_TASK. A Service is not in a task, so the system throws AndroidRuntimeException. Even with the flag, Android 10+ usually blocks starts from the background; post a notification with a PendingIntent instead.
  • Overriding onBackPressed() for custom back logic. It is deprecated, and with predictive back enabled the system no longer calls it. Use OnBackPressedDispatcher.addCallback (with viewLifecycleOwner in a Fragment) or BackHandler.
  • Using singleInstance when singleTask suffices. A singleInstance activity lives alone in its own task, so any activity it starts goes into another task, and Recents can show two entries for your app. Use it only when the activity must never share a task.
  • Forgetting FLAG_ACTIVITY_SINGLE_TOP with CLEAR_TOP. CLEAR_TOP alone finishes and recreates a standard target, losing its in-memory state. Adding SINGLE_TOP reuses the existing instance and calls onNewIntent.
  • Using FLAG_ACTIVITY_CLEAR_TASK without NEW_TASK. It is ignored on its own, so the old screens stay in the task.
  • Making the launcher Activity singleTask "to avoid duplicates". Every launch then finishes everything above it, so returning from the home screen icon can throw away the user's place. Fix the duplicate launches instead.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Explain what a task is and how the back stack works.”

“What are the four launch modes and when would you use each?”

“What happens if you start an Activity from a Service?”

“How do you handle Back navigation in a modern Android app?”

Quiz

What does FLAG_ACTIVITY_CLEAR_TOP do when the target activity is already in the task?

Which launch mode keeps at most one instance and finishes the activities above it when it is reused?

What must you add when starting an Activity from a Service?

What replaces overriding the deprecated onBackPressed() method?

0 of 4 answered

Mini task

Hands-on: watch launch modes change the stack (15 min)

  1. Create a project with two Activities: HomeActivity and DetailActivity. Log onCreate and onNewIntent in DetailActivity.
  2. In AndroidManifest.xml, set DetailActivity to android:launchMode="singleTop".
  3. In HomeActivity, add a button that opens DetailActivity with an extra count = 1.
  4. In DetailActivity, add an "Open again" button that starts DetailActivity with count + 1. Override onNewIntent(), call setIntent(intent), and show the count in a TextView.
  5. Run the app. Open DetailActivity from Home, then press "Open again" twice. Confirm onCreate ran once and onNewIntent ran twice. Press Back once: you should be on Home.
  6. Change the launch mode to standard and repeat. Confirm onCreate ran three times, and that you need Back three times to reach Home. Check with adb shell dumpsys activity activities.
  7. Add an "Open Home" button to DetailActivity that starts HomeActivity normally. In HomeActivity, make the button add FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP. Go Home, Detail, Home, then press the button. Confirm the original DetailActivity gets onNewIntent and the second HomeActivity is gone.

Done condition: You can explain, in your own words, why onNewIntent fires in step 5 but not in step 6, and what CLEAR_TOP did in step 7.

Next: Thinking in Compose