Skip to main content

Understanding the Android Activity Lifecycle — From Views to Compose

Updated 13 min readMarkdown
Understanding the Android Activity Lifecycle — From Views to Compose

If you're moving from the pre-Compose era to Jetpack Compose, there's good news: the Activity lifecycle hasn't changed at all. What's changed is how you fill the screen once the Activity exists. This post walks through the mental model, the full lifecycle, what happens under the hood when you launch an Activity, and how launch modes and intent flags control the back stack.

The Big Picture: Activity as a Container

Think of an Activity as a window or screen container that the Android OS manages. Everything else is just what you put inside that window.

  • Pre-Compose: you filled the window with a tree of Views defined in XML.

  • Compose: you fill the same window with a tree of composable functions.

Note on the Activity Class: In the Compose era, you don't extend the base android.app.Activity class. Compose requires a ComponentActivity (or its subclass AppCompatActivity) because it provides the LifecycleOwner and OnBackPressedDispatcher that the Compose framework relies on under the hood to manage state and navigation.

The window and its lifecycle rules are identical either way — only the content inside changes.

Aspect Pre-Compose (Views) Compose Era
UI definition XML + findViewById Kotlin functions (@Composable)
Updating UI Imperative (text = "...") Declarative (state changes → recompose)
Entry point setContentView(...) setContent { }
Lifecycle Same Same (Activity still owns it)
Configuration changes Manual handling needed Handled automatically by Compose + ViewModel
Performance View hierarchy can be heavy Recomposition updates only what changed
Navigation Activities / Fragments Usually one Activity + Navigation Compose

In the old model, you declared an activity in AndroidManifest.xml, inflated a layout with setContentView(R.layout.your_layout), and imperatively told each view how to update. In Compose, you declare what the UI should look like given some state, and the framework figures out which parts actually need to be redrawn — it doesn't repaint the whole hierarchy just because one value changed.

The Three Lifetimes

Before diving into individual callbacks, it helps to group them into three overlapping "lifetimes":

Lifetime From → To Meaning Typical use
Entire lifetime onCreate → onDestroy Whole existence of this Activity instance Create/destroy expensive objects
Visible lifetime onStart → onStop User can see the Activity UI-related resources
Foreground lifetime onResume → onPause User can interact with it Exclusive resources (camera, etc.)

The Lifecycle Callbacks

onCreate() — The first entry point. This is where you inflate/initialize the view. Nothing happens in the lifecycle before this.

onStart() — The view is about to become visible. Good place to initialize LiveData/Flow observers or broadcast receivers.

onResume() — The view is ready for direct user interaction. Register listeners and observers here — but avoid heavy initialization work in this callback.

onPause() — Called when the user navigates away, or when a dialog/bottom sheet pops up over the Activity. The view may still be visible, just not directly interactive. (When a dialog or transparent Activity appears on top, the underlying Activity's lifecycle typically stops progressing at onPause rather than continuing to onStop.) This is where you should unregister exclusive-resource listeners like camera or location updates.

onStop() — Called when the Activity is no longer visible at all (user navigated to a different screen). Stop listening for broadcast-type updates here.

onDestroy() — The final lifecycle call. Historically triggered by a simple back-press or configuration change. Clean up resources here. Modern Android note: With Android 14+ Predictive Back Navigation, you shouldn't rely on standard Activity popping for back events. Instead, intercept back presses using OnBackPressedDispatcher (or BackHandler in Compose) so the OS can animate the back gesture gracefully before the Activity is destroyed

onRestart() — Fires when the user navigates back to an Activity that was previously stopped. Example: app opens → Screen B → Screen C → back-press returns to B → onRestart() fires on B. It's only called if onStop() had previously been called on that same instance; it's skipped if the user never left in the first place.

onSaveInstanceState() — Called when the system anticipates the Activity might be destroyed and recreated (rotation, backgrounding under memory pressure), so you can stash UI state into a Bundle.

Version note: Timing here changed across Android versions. Prior to Android 9 (Pie), onSaveInstanceState() was called before onStop(), with no strict guarantee about its order relative to onPause(). For apps targeting API 28+, it's now guaranteed to be called after onStop(). Either way, it won't fire if the user explicitly finishes the Activity (e.g., via finish() or back-pressing out of the app entirely) — it's only for system-initiated recreation.

onRestoreInstanceState() — Rarely used directly anymore. In Compose, you'll rarely touch manual Bundle stashing at the Activity level. For UI state, rememberSaveable handles orientation changes. For business logic that must survive system-initiated process death, you should use SavedStateHandle injected directly into your ViewModel. This modernizes state preservation without shuffling Bundles in the Activity callbacks.

What Happens on Screen Rotation

User rotates phone
        │
        ▼
┌─────────────────────────────┐
│     OLD Activity            │
│  onPause()                  │
│  onStop()                   │
│  onSaveInstanceState()  ←─── saved here (API 28+)
│  onDestroy()                │  ← old instance dies
└─────────────────────────────┘
        │
        ▼
┌─────────────────────────────┐
│     NEW Activity            │
│  onCreate(Bundle)       ←─── saved data arrives here
│  onStart()                  │
│  onResume()                 │
└─────────────────────────────┘

Why destroy and recreate instead of just re-laying-out? Because historically the layout itself could differ between orientations — activity_main.xml for portrait vs. a distinct landscape variant — so Android takes the safe route of tearing down and rebuilding the UI to match the new configuration.

Why Register Listeners Where You Do

Broadcast receivers → onStart() / onStop(). These are fine to leave active even when the Activity isn't the interactive foreground — if a dialog pops up, you still want to keep receiving system broadcasts. Tying them to onResume/onPause instead means they'd drop out the moment any overlay appears.

Camera, location, gesture listeners → onResume() / onPause(). These consume battery and, in some cases, exclusive hardware access (only one screen should be actively pulling from the camera at a time). If a dialog appears over your camera screen, you genuinely want to release that resource — so tying it to the foreground lifetime, not just visibility, is correct. Registering location updates as early as onStart() would mean they keep streaming — and draining battery — even while the user isn't actively interacting with your screen.

How an Activity Actually Gets Launched (Under the Hood)

  1. You call startActivity(), which routes through a system service.

  2. ActivityTaskManagerService (ATMS) inspects the Activity's launchMode and any Intent flags to decide whether to reuse an existing instance, clear part of the stack, or create a fresh one. ATMS maintains the internal record of the task/back-stack.

  3. Your app's ActivityThread — the main thread of your process — receives a "launch this Activity" message.

  4. The system uses reflection to instantiate your Activity class. (This is exactly why Activities can't have custom constructors that take parameters — the system, not you, is the one calling new.)

  5. Instrumentation.callActivityOnCreate() runs, which eventually invokes your onCreate().

  6. Every Activity gets a PhoneWindow, whose root view is a DecorView (a specialized FrameLayout that holds the status bar, nav bar area, and your actual content).

  7. Your content attaches to that DecorView:

    • Pre-Compose: setContentView(layout) inflates your XML and adds it.

    • Compose: setContent { } adds a ComposeView and composition begins.

  8. ActivityThread continues driving onStart(), onResume(), etc., as visibility/focus decisions come in from the WindowManager and ATMS.

  9. When the user navigates away, ATMS decides the new state and ActivityThread calls onPause() → onStop() → possibly onDestroy().

The key takeaway: you never construct an Activity yourself. The system owns creation, ownership, and destruction end-to-end — you only supply the code that runs inside the callbacks.

Launch Modes: Controlling Instances and Stack Position

Three things govern how Activities are created and where they live:

  1. launchMode — how many instances can exist, and where in the stack.

  2. taskAffinity — which task (group of Activities) this one prefers to belong to.

  3. Intent flags — runtime instructions passed via startActivity().

Attribute Default Meaning
launchMode "standard" New instance every time
taskAffinity Your app's package name All your Activities prefer to share one task
Intent flags None (unless launched from a non-Activity context) Normal behavior

standard (default)

A new instance is created every single time. Multiple instances of the same Activity can coexist in one task.

A → B → C → B → C   (two instances each of B and C)

singleTop

If the target is already at the top of the stack, it's reused (onNewIntent() fires) instead of creating a new instance. If it's not at the top, a new instance is created as usual.

Use case: a notification that reopens the same screen the user is already viewing.

Stack: A → B → C
Launch C again (already top) → A → B → C   (same instance, onNewIntent())
Launch B instead (not top)   → A → B → C → B   (new instance)

singleTask

Only one instance can exist system-wide, and it's always the root of its task. Relaunching it brings its task to the front and destroys everything stacked above it.

Stack: A → B → C → D   (B is singleTask)
Relaunch B → B   (C and D are destroyed; onNewIntent() called on B)

Common for an app's main/home screen or browser-style behavior.

singleInstance

Like singleTask, but the Activity is the only thing allowed in its task — nothing else can join it. Rare in practice (launcher, dialer-type apps).

Key Intent Flags

val intent = Intent(this, TargetActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
Flag Effect
FLAG_ACTIVITY_NEW_TASK Start in a new task, or bring an existing one to front
FLAG_ACTIVITY_SINGLE_TOP Same effect as launchMode="singleTop"
FLAG_ACTIVITY_CLEAR_TOP If the target exists in the stack, clear everything above it and deliver the Intent
FLAG_ACTIVITY_CLEAR_TASK Wipe the entire task and start fresh
FLAG_ACTIVITY_NO_HISTORY Don't keep this Activity in the back stack at all

Note that Intent flags generally override whatever launchMode is declared in the manifest.

What is onNewIntent()?

onNewIntent() is a special callback that is called instead of creating a new instance of the Activity.

When is it called?

  • When an existing instance of the Activity is reused.

  • Happens mainly with:

    • launchMode = "singleTop"

    • launchMode = "singleTask"

    • launchMode = "singleInstance"

    • Or when using flags like FLAG_ACTIVITY_SINGLE_TOP / FLAG_ACTIVITY_CLEAR_TOP

Important points about onNewIntent():

Kotlin

override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    setIntent(intent)          // Very important! Update the Intent
    // Now handle the new data
}
  • Always call setIntent(intent) inside it so that subsequent calls to getIntent() return the latest Intent.

  • The Lifecycle Flow: It is called before onResume(). If the Activity is already in the foreground, the system temporarily pauses it, resulting in this flow: onPause() → onNewIntent() → onResume().

  • If the Activity was in the background (stopped), the flow is: onStart() → onNewIntent() → onResume().

  • It is not part of the normal lifecycle (not between onPause and onResume).

  • The Activity is already in the Resumed state when this is called.

  • Always call setIntent(intent) so that getIntent() returns the latest Intent.

CLEAR_TOP + SINGLE_TOP — the classic "go home" pattern:

intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP

CLEAR_TOP alone clears everything above the target, but if the target happens to already be on top, it would still spin up a fresh instance. Adding SINGLE_TOP prevents that — if it's already on top, it's simply reused. This is the pattern behind bottom-navigation "Home" buttons in apps like food-delivery or ride-hailing apps: navigating home from deep inside the app clears the stack down to a single, reused Home instance.

NEW_TASK + CLEAR_TASK — the "clean slate" pattern, typically used after logout/login:

val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
finish()

After this, pressing back exits the app entirely — no prior screens remain.

NEW_TASK + CLEAR_TOP — useful when launching from a notification, BroadcastReceiver, or Service, where you want to bring an existing task forward and clear above a specific target screen (e.g., a notification tap that should land on "Order Details" and drop everything above it).

SINGLE_TOP alone — prevents a duplicate instance if the target is already on top; common for notifications reopening the same screen.

CLEAR_TOP alone — clears everything above the target but still creates a fresh instance of it even if it was already on top (rare in practice, since SINGLE_TOP usually gets paired in).

Bridging the Gap: Observing Lifecycle in Compose

Since Composable functions don't have overrides like onStart() or onResume(), how do you register those location or camera listeners we talked about earlier?

For a long time, the standard approach was using a DisposableEffect combined with a LocalLifecycleOwner to listen to state changes. While that still works, modern Compose (androidx.lifecycle:lifecycle-runtime-compose) gives us dedicated, readable effects:

Kotlin

@Composable
fun CameraScreen() {
    // Fires when the Activity hits onStart / onStop
    LifecycleStartEffect(Unit) {
        // e.g., connect to a broadcast receiver
        
        onStopOrDispose {
            // cleanup when stopped
        }
    }

    // Fires when the Activity hits onResume / onPause
    LifecycleResumeEffect(Unit) {
        // e.g., request exclusive camera access
        
        onPauseOrDispose {
            // release camera access
        }
    }
}

These effects perfectly map your Composable UI directly to the visible (onStart) and foreground (onResume) lifetimes of the host Activity, without you ever needing to touch the Activity file itself.

Takeaway

The Activity lifecycle is the one constant across the pre-Compose and Compose eras — what changes is purely how you describe and update content inside it. Understanding why certain callbacks pair with certain resource types (broadcast receivers with visibility, exclusive hardware with foreground focus) makes the whole system feel a lot less like a list of callbacks to memorize and more like a coherent set of trade-offs the OS is managing on your behalf.

About the author

  • I started as an Android developer — 7+ years, most of it at GoTo/Gojek , and have since moved into backend engineering as well, working with Go, Kafka, Redis, and distributed systems. These days I split my time across both, plus the occasional LLM-driven side project. This blog is where I write about what I actually run into on the job: production issues I've debugged, practical tutorials, and the small productivity wins that make the day-to-day easier. Currently working as an independent contractor and open to full-time and freelance roles across Android and backend engineering , feel free to reach out.

No comments yet. Be the first to comment.