Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 104 ยท Navigation

Back Stack, Launch Modes and Deep Links

Control the Android back stack with popUpTo, launchSingleTop and saveState, understand activity launch modes, handle deep links and app links, and support predictive back.

Every time you call navigate, a destination is pushed on the back stack, and every time the user presses Back, one is popped. That is fine for a simple list and detail flow, but real apps need more control. After login, the user must not be able to press Back and land on the login screen again. Tapping the same bottom tab twice must not stack two copies of it. A link in an email must open a product page and still give the user a sensible Back button.

This lesson covers the tools for that: popUpTo, launchSingleTop, state saving, activity launch modes, deep links and predictive back. It builds on Navigation Compose Basics and Passing Arguments and Results. The Navigation library needs the Android SDK, so the Navigation code below is read-only; the TryIt blocks are stand-ins that implement the same stack rules and URL matching in plain Kotlin so you can watch what happens.

The back stack as a list

Think of the back stack as a list of entries. The last entry is the screen on display. navigate appends, Back removes the last one, and when the stack is empty the activity finishes.

flowchart LR
    A["Home"] --> B["Home, Detail 1"]
    B --> C["Home, Detail 1, Detail 2"]
    C -- "Back" --> B
    B -- "Back" --> A

Each navigate pushes an entry; each Back pops one.

With the type-safe API, a navigate call can take a small builder block with options:

Kotlin
// read-only example: needs Navigation Compose
navController.navigate(Home) {
    popUpTo<Login> { inclusive = true }
    launchSingleTop = true
}

The options are applied together: first the stack is trimmed, then the destination is pushed (or skipped, if it is already on top and launchSingleTop is set).

popUpTo: removing entries while you navigate

popUpTo pops destinations off the stack before the new one is pushed. You name the destination to pop back to:

  • popUpTo<Home>() removes everything above Home but keeps Home itself.
  • popUpTo<Home> { inclusive = true } removes Home as well.

The login case is the classic one. The stack is [Splash]; you show Login; after success you go to Home and remove both earlier screens:

Kotlin
// read-only example: leaving the login flow
navController.navigate(Home) {
    popUpTo<Splash> { inclusive = true }   // clears Splash and Login
}

Because Login sat above Splash, popping up to Splash inclusively removes both. After this, Back on Home leaves the app instead of returning to a login form.

launchSingleTop: no duplicates

launchSingleTop = true says: if the destination I am navigating to is already on top of the stack, reuse it instead of pushing a copy. It matters when the same action can fire twice, for example a double tap on a button, a tab icon, or a notification that targets the screen you are already viewing.

Without it, double tapping a "Details" button produces [Home, Details, Details] and the user has to press Back twice. With it, the second navigation is ignored (the existing entry may receive the new arguments).

A back stack you can poke

This stand-in implements the rules above on a list of strings. It is not the real NavController, but the stack semantics are the same: pop first, then push, with an optional single-top check.

Kotlin Back stack with popUpTo and singleTop (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Run it and read the output top to bottom. After the login step the stack is just [home]. The first detail/1 with singleTop is ignored, while the plain one pushes a duplicate. The last navigate("home", popUpTo = "home") trims everything above home, then pushes home again, so the screen is rebuilt on a fresh entry.

saveState and restoreState

Sometimes you want to leave a part of the stack without losing it. Bottom navigation is the standard example: switching from the Feed tab to the Profile tab should not throw away where the user was deep inside Feed. The options are:

Kotlin
// read-only example: switching top-level destinations
navController.navigate(route) {
    popUpTo(navController.graph.findStartDestination().id) {
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}

saveState = true on popUpTo stores the entries it pops (and their saved UI state) instead of discarding them. restoreState = true on a later navigate to that destination brings the saved entries back. Together with launchSingleTop this gives each tab its own memory. The next lesson builds the full pattern and a stand-in for it.

Activity launch modes

Navigation Compose usually lives inside one activity, but the system also has a back stack of activities, called a task. How a new activity instance joins a task is its launch mode, set in the manifest with android:launchMode:

Mode Behavior
standard (default) A new instance is created on every launch, even if one is already on top
singleTop If an instance is on top of the task, it is reused and receives onNewIntent
singleTask One instance per task: launching it again brings it forward and destroys the activities above it
singleInstance Like singleTask, but the activity is alone in its own task

You can also set the behavior per launch with intent flags such as FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP. launchSingleTop in navigation is the same idea one level down, inside a single activity. A single-activity app mostly needs standard or singleTop; exotic modes are for special entry points. If you see onNewIntent in your Logcat after tapping a notification, the activity was reused and you need to handle the fresh intent, for example by calling navController.handleDeepLink(intent).

A deep link is a URI that opens a specific screen. There are three kinds:

  • Custom scheme links such as myshop://product/42. Anyone can register the same scheme, so the system may show a chooser.
  • Web links (https://example.com/product/42) that your app declares an intent filter for. A browser or other app may still handle them.
  • App Links are verified web links. The system checks a JSON file that your domain serves, and if it matches your app's signing certificate, links open directly in your app with no chooser.

Declaring a deep link takes two steps. First, the manifest tells the system that the activity can handle the URI:

XML
<!-- read-only example: AndroidManifest.xml -->
<activity android:name=".MainActivity" android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" android:host="example.com" android:pathPrefix="/product" />
    </intent-filter>
</activity>

autoVerify="true" asks the system to verify the domain at install time; your site must serve /.well-known/assetlinks.json listing the package name and certificate fingerprint. Second, the destination declares which URI patterns it accepts:

Kotlin
// read-only example: a destination with a deep link
composable<Product>(
    deepLinks = listOf(
        navDeepLink<Product>(basePath = "https://example.com/product"),
    ),
) { entry ->
    val product = entry.toRoute<Product>()
    ProductScreen(product.id)
}

The path segment and query parameters are mapped onto the fields of Product, just like route arguments. When the activity starts from the link, the NavController reads the intent and navigates. It also builds a synthetic back stack from the start destinations of the graphs that contain the target, so Back from the product page goes to a real screen rather than closing the app straight away.

Treat every deep link as untrusted input. Any app, web page or QR code can send your activity a URI. Validate ids, never perform a destructive action just because a link says so, and show a confirmation screen for sensitive operations.

The stand-in below does the same work in plain Kotlin: it matches a URI against patterns with , extracts the arguments, and builds a back stack made of the parent screen followed by the target.

Kotlin Deep link matching with a synthetic back stack (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that https://example.com/product/ (empty id) fails to match, and an unknown path falls back to the start screen. Your real code should make the same decisions: reject malformed links and have a safe default.

Predictive back

On recent Android versions the Back gesture can show a preview of where it leads: the current screen shrinks and slides while the previous one appears underneath, and the user can cancel by moving the finger back. This is predictive back. You opt in with one manifest attribute:

XML
<!-- read-only example: AndroidManifest.xml -->
<application android:enableOnBackInvokedCallback="true" ... >

Compose and Navigation Compose cooperate with it, so standard screens animate for free. The one thing you must change is any code built on the old onBackPressed() override, which no longer works with the new system. Use BackHandler instead, for example to protect unsaved work:

Kotlin
// read-only example: intercepting Back in Compose
BackHandler(enabled = hasUnsavedChanges) {
    showDiscardDialog = true
}

Because BackHandler is only enabled while there are unsaved changes, normal Back behavior returns as soon as the flag is false. For custom animations while the gesture is in progress, Compose provides PredictiveBackHandler, which exposes the gesture progress as a flow.

Common mistakes

  • Forgetting popUpTo after login or onboarding, so Back returns to the login screen.
  • Using launchSingleTop with different arguments, then wondering why the screen did not change. Navigate with new arguments to a screen that handles argument updates, or pop first.
  • Deep link filters without BROWSABLE, so links from a browser never reach the app.
  • Trusting link parameters. Parse and validate them like user input.
  • Overriding onBackPressed in an app that supports predictive back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The stack is [splash, login]. You call navigate(home) with popUpTo(splash) { inclusive = true }. What is the stack afterwards?

    popUpTo removes entries above splash and, because it is inclusive, splash too. Only then is home pushed, so the stack is [home].
  2. 2. What does launchSingleTop = true do?

    If the destination is already on top, no new entry is created. This avoids stacks like [Home, Details, Details] caused by double taps.
  3. 3. What makes a web link an Android App Link rather than a plain web link?

    With autoVerify and a matching assetlinks.json, the system trusts that you own the domain and opens links in your app without a chooser.
  4. 4. Which API should replace an old onBackPressed override when you support predictive back?

    BackHandler registers with the modern back dispatcher, which is what the system's back gesture and preview animation use.

Summary

  • The back stack is a list: navigate pushes, Back pops, and an empty stack finishes the activity.
  • popUpTo trims the stack before pushing; inclusive = true also removes the named destination. Use it to leave login and onboarding flows.
  • launchSingleTop avoids duplicate entries; saveState and restoreState let you leave and later return to part of a stack.
  • Activity launch modes (standard, singleTop, singleTask, singleInstance) control how activities join a task; single-activity apps rarely need more than the default.
  • Deep links need a manifest intent filter and a destination pattern; verified App Links open without a chooser. The NavController synthesizes a parent back stack.
  • Predictive back is opt-in via the manifest; use BackHandler, never onBackPressed.
  • The Navigation code is read-only; the TryIts are plain-Kotlin stand-ins for the stack rules and the link matcher.

Next: Bottom Navigation and Nested Graphs