Tasks and the back stack
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, andNEW_TASK, and expect precise answers. - Modern back handling with
OnBackPressedDispatcherand 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.
standardmode: 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:
| Mode | Behaviour |
|---|---|
standard (default) | New instance, pushed on top |
singleTop | If an instance is already on top, reuse it and call onNewIntent; otherwise a new instance |
singleTask | At most one instance. If it exists, its task comes forward, everything above it is finished, and it gets onNewIntent |
singleInstance | Like 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 itstaskAffinity, creating that task if needed. Required when the caller is not an Activity (aService, aBroadcastReceiver, 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. Astandardtarget is itself finished and recreated, unless you also addSINGLE_TOP.FLAG_ACTIVITY_SINGLE_TOP: if the target is already on top, reuse it (likesingleTop, for this launch only).FLAG_ACTIVITY_CLEAR_TASK: used together withNEW_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.
Pick how the next screen is launched, then open screens and press Back.
- Screen Avisible
- 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.
standardis the default launch mode: a new instance is created and pushed on top every time.singleTopreuses the instance only if it is on top, and callsonNewIntent()instead ofonCreate(). If it is lower in the stack, a new instance is created.singleTaskkeeps at most one instance. Reusing it finishes every activity above it in its task.singleInstancekeeps one instance alone in its own task. It is rarely needed in modern apps.- In
onNewIntent(), callsetIntent(intent)if later code readsintent, otherwiseintentstill returns the old one. FLAG_ACTIVITY_NEW_TASKis mandatory when starting an Activity from aService,BroadcastReceiver, or the Application context. Since Android 10, starts from the background are also restricted; use a notification instead.FLAG_ACTIVITY_CLEAR_TOPalone finishes and recreates astandardtarget; addSINGLE_TOPto keep the existing instance.FLAG_ACTIVITY_CLEAR_TASKonly works together withFLAG_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. UseOnBackPressedDispatcher.addCallback()(Views) orBackHandler(Compose). With predictive back enabled,onBackPressed()is not called at all. - Setting
taskAffinityto 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_TOPkeeps the existingDetailActivityand delivers the intent toonNewIntent;CLEAR_TOPalone would finish and recreate it.NEW_TASK or CLEAR_TASKfinishes every activity in the task, so Back fromLoginActivitycannot return to signed-in screens.addCallback(this, ...)removes the callback automatically when the Activity is destroyed; in a Fragment passviewLifecycleOwner.- For predictive back, keep the callback's
isEnabledup to date ahead of time instead of deciding insidehandleOnBackPressed, 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
- A notification opened
OrderDetailActivitydirectly through aPendingIntent. - 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.
- Declared
android:parentActivityName=".OrderListActivity"and built thePendingIntentwithTaskStackBuilder(addNextIntentWithParentStack, thengetPendingIntentwithFLAG_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.
- The app's main Activity was declared
singleTaskand 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.
- Changed the main Activity back to
standard(orsingleTopwhere repeated intents should reuse the top instance). - Used
FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOPonly 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 withadb 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 aPendingIntentinstead. - Overriding onBackPressed() for custom back logic. It is deprecated, and with predictive back enabled the system no longer calls it. Use
OnBackPressedDispatcher.addCallback(withviewLifecycleOwnerin a Fragment) orBackHandler. - Using singleInstance when singleTask suffices. A
singleInstanceactivity 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_TOPalone finishes and recreates astandardtarget, losing its in-memory state. AddingSINGLE_TOPreuses the existing instance and callsonNewIntent. - 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)
- Create a project with two Activities:
HomeActivityandDetailActivity. LogonCreateandonNewIntentinDetailActivity. - In
AndroidManifest.xml, setDetailActivitytoandroid:launchMode="singleTop". - In
HomeActivity, add a button that opensDetailActivitywith an extracount = 1. - In
DetailActivity, add an "Open again" button that startsDetailActivitywithcount + 1. OverrideonNewIntent(), callsetIntent(intent), and show the count in aTextView. - Run the app. Open
DetailActivityfrom Home, then press "Open again" twice. ConfirmonCreateran once andonNewIntentran twice. Press Back once: you should be on Home. - Change the launch mode to
standardand repeat. ConfirmonCreateran three times, and that you need Back three times to reach Home. Check withadb shell dumpsys activity activities. - Add an "Open Home" button to
DetailActivitythat startsHomeActivitynormally. InHomeActivity, make the button addFLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP. Go Home, Detail, Home, then press the button. Confirm the originalDetailActivitygetsonNewIntentand the secondHomeActivityis 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.