Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 104 ยท Activities and the Lifecycle

The Activity Lifecycle

Understand the Android Activity lifecycle: every callback from onCreate to onDestroy, visible versus focused, what belongs in each one and how process death works.

An activity does not simply "run". The system creates it, shows it, covers it, hides it, brings it back and finally destroys it, and it tells your class about each step by calling a lifecycle callback. These steps happen for reasons you do not control: the user presses Home, a phone call arrives, the screen rotates, memory runs low. If you load data in the wrong callback, forget to release a camera or ignore the possibility that the process is killed, the app misbehaves in ways that are hard to reproduce.

This lesson walks through the callbacks in order, explains the difference between an activity being visible and being focused, and shows what to do in each callback. The real lifecycle belongs to the Android runtime, so the Android snippets are read-only and the TryIt blocks are stand-ins: small state machines that enforce the same legal transitions and print the callbacks. The previous lesson, Activities and setContent, introduced the activity itself.

The callbacks, in order

The lifecycle has six main callbacks. Three of them come in pairs that open and close a stretch of time:

Kotlin
// read-only example: needs the Android SDK
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("Life", "onCreate")
        setContent { HomeScreen() }
    }

    override fun onStart() {
        super.onStart()
        Log.d("Life", "onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.d("Life", "onResume")
    }

    override fun onPause() {
        Log.d("Life", "onPause")
        super.onPause()
    }

    override fun onStop() {
        Log.d("Life", "onStop")
        super.onStop()
    }

    override fun onDestroy() {
        Log.d("Life", "onDestroy")
        super.onDestroy()
    }
}

By convention, the "up" callbacks (onCreate, onStart, onResume) call super first, and the "down" callbacks (onPause, onStop, onDestroy) call super last, so your code runs in the right order relative to the framework's.

Callback Called when The pair
onCreate The activity instance is first created onDestroy
onStart The activity becomes visible onStop
onResume The activity gains focus and the user can interact onPause
onPause The activity loses focus (it may still be visible) onResume
onStop The activity is no longer visible onStart
onDestroy The activity is finishing or being recreated onCreate

There is also onRestart, called after onStop when the user comes back, just before onStart. Most apps never need it.

stateDiagram-v2
    [*] --> Created: onCreate
    Created --> Started: onStart
    Started --> Resumed: onResume
    Resumed --> Paused: onPause
    Paused --> Resumed: onResume
    Paused --> Stopped: onStop
    Stopped --> Started: onRestart + onStart
    Stopped --> Destroyed: onDestroy
    Created --> Destroyed: onDestroy
    Destroyed --> [*]

The lifecycle as a state machine: the system chooses the transitions, you react to them.

Visible versus focused

Two words matter here:

  • Visible is the time between onStart and onStop. The user can see at least part of the activity.
  • Focused (the resumed state) is the time between onResume and onPause. The activity is in the foreground and receives input.

An activity can be visible without being focused. A permission dialog from the system, a transparent activity on top, or a second window in split-screen mode all pause an activity that you can still see. That is why you should not stop animations or video in onStop alone: the user may still be looking at the screen.

The stand-in below enforces the legal transitions. Each callback may only be called from certain states; the machine throws IllegalStateException otherwise (the real framework simply never makes those calls). It also reports whether the activity is visible and focused after each step.

Kotlin A lifecycle state machine (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.

What to do in each callback

onCreate runs once per instance. Do one-time setup here: call setContent, set up the ViewModel, register things that last as long as the activity. Do not do slow work such as reading files or the network on the main thread; start a coroutine or use a ViewModel. Startup time is measured from here.

onStart and onStop bracket the visible time. Start and stop things that matter only while the user can see the screen: for example listening to location updates for a map or registering a broadcast receiver that updates visible UI.

onResume and onPause bracket the focused time. Use them for things that need exclusive or interactive state, such as a camera preview, sensors or a game loop. Keep onPause fast: the next activity cannot appear until onPause returns.

onDestroy is the last callback, but it is not guaranteed. Never rely on it to save user data. Use it only to release resources you created in onCreate, and remember that after process death it is not called at all.

With Compose and AndroidX there is rarely a need to override these methods. Instead, observe the lifecycle from anywhere with a LifecycleEventObserver, or collect flows safely with repeatOnLifecycle and collectAsStateWithLifecycle, which you will meet in StateFlow and collectAsStateWithLifecycle. That keeps the setup and teardown code next to each other and out of the activity.

Kotlin
// read-only example: lifecycle-aware component with an observer
class LocationTracker : DefaultLifecycleObserver {
    override fun onStart(owner: LifecycleOwner) { /* begin updates */ }
    override fun onStop(owner: LifecycleOwner) { /* end updates */ }
}

// in the activity:
lifecycle.addObserver(LocationTracker())

Everyday user actions, step by step

The callbacks follow what the user does. Here are the common sequences for one activity:

User action Callbacks
Launch the app onCreate, onStart, onResume
A dialog or permission prompt covers part of the screen onPause (then onResume when dismissed)
Press Home or switch apps onPause, onStop
Return to the app onRestart, onStart, onResume
Press Back on the root screen onPause, onStop, onDestroy
Rotate the device onPause, onStop, onDestroy, then onCreate, onStart, onResume on a new instance

Rotation is the surprising one: by default the activity is destroyed and a new one is created. Configuration Changes and Saved State shows how to keep your data.

Process death

When the app is in the background, the system may kill its whole process to reclaim memory, and it does not tell you. All the objects in memory vanish, including every ViewModel, and onDestroy is not called. When the user returns, Android starts a new process and recreates the activity, passing the saved Bundle to onCreate so you can restore what you had saved.

Which processes die first depends on how important they are: a process with a focused activity is the last to die, one with only stopped activities is among the first. This is also why you must save important state while the activity is still being stopped. You will practice it in the next lessons.

The second stand-in plays user actions against the machine. Each action expands to the callbacks above. The "kill" action models process death: the state is lost without a single callback, and the next launch starts from scratch.

Kotlin Playing user actions through the lifecycle (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.

Common mistakes

  • Doing slow work in onCreate or onResume. It blocks the first frame. Move it to a coroutine in a ViewModel.
  • Saving data in onDestroy. It may never run. Save in onStop or, better, continuously as the user edits.
  • Holding Activity references in long-lived objects (singletons, static fields, a ViewModel). When the activity is destroyed, the reference keeps it in memory: a memory leak. Hold applicationContext instead if you need a context.
  • Starting listeners in onCreate and never stopping them. Pair every start with a stop in the matching callback.
  • Assuming the activity is created once. With rotation, dark mode, language and font-size changes it can be created many times in one session.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is an activity visible but not focused?

    Visible means between onStart and onStop; focused means between onResume and onPause. After onPause and before onStop the activity is still visible but not interactive.
  2. 2. Which callback pair brackets the time the user can see the activity?

    onStart makes the activity visible and onStop hides it. onResume and onPause bracket the narrower focused period.
  3. 3. What happens to onDestroy when the system kills your process to free memory?

    Process death is silent: memory is simply reclaimed. Anything that must survive has to be saved earlier, for example in onStop or as the user types.
  4. 4. What does a rotation do to the activity by default?

    A configuration change recreates the activity: onPause, onStop, onDestroy on the old instance and onCreate, onStart, onResume on the new one.

Summary

  • The system drives the lifecycle: onCreate, onStart, onResume, then onPause, onStop, onDestroy, plus onRestart when coming back from stopped.
  • Visible is onStart to onStop; focused is onResume to onPause. An activity can be visible without focus.
  • Do one-time setup in onCreate, visible-only work in onStart/onStop, interactive work in onResume/onPause.
  • onDestroy is not guaranteed: never save user data there, and expect process death with no callbacks.
  • Prefer lifecycle-aware components and observers over overriding many callbacks.
  • Rotation and other configuration changes recreate the activity.
  • The Android code is read-only; the TryIts model the legal transitions and sequences.

Next: Intents and Launching Other Screens