Skip to content

Intermediate: Android basics · Android Studio and your first app · topic 20 of 50 · 30 min

Activities and the lifecycle

Explanation

An Activity is an entry point that shows a screen. Android moves it through lifecycle states and calls onCreate, onStart, onResume, onPause, onStop and onDestroy as the user opens, leaves and returns to it. On a configuration change such as rotation, the activity is destroyed and recreated, so screen state must be kept in a ViewModel or with rememberSaveable.

What is an Activity?

An Activity is one of Android's app components: an entry point that the system can start, which shows a user interface. Older apps had one activity per screen. Modern Compose apps usually have a single activity (MainActivity) and switch screens inside it with navigation (module 7). Your MainActivity extends ComponentActivity.

Why a lifecycle?

Phones are busy. A call comes in, the user switches to WhatsApp, the screen turns off, memory runs low. Android must tell your activity what is happening so it can pause a video, save a draft or stop using the camera. These notifications are the lifecycle callbacks: functions Android calls at each change.

output
        onCreate()      created: set up the UI (setContent)
            |
        onStart()       visible
            |
        onResume()      in front, user can interact       <--+
            |                                                  |
        onPause()       partly hidden or losing focus  -------+ (back to onResume)
            |
        onStop()        no longer visible          --> onRestart() --> onStart()
            |
        onDestroy()     finishing, or recreated after a configuration change
The main lifecycle path of an activity.
CallbackTypical use
onCreateOne-time setup: call setContent { } with your Compose UI
onStart / onStopStart or stop work that only matters while visible (location updates, animations)
onResume / onPauseThings that need focus: camera preview, pausing a video
onDestroyFinal cleanup (not guaranteed to run if the process is killed)
kotlin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { Text("Hello") }
        Log.d("Life", "onCreate")
    }
    override fun onStart() { super.onStart(); Log.d("Life", "onStart") }
    override fun onStop() { super.onStop(); Log.d("Life", "onStop") }
}
Always call the super version first. Watch the messages in Logcat as you rotate and leave the app.

Configuration changes

A configuration change is a change to the device setup: rotating the screen, switching to dark mode, changing the language, resizing on a foldable. By default Android destroys and recreates the activity, calling onDestroy then onCreate again, so the UI can load resources for the new configuration. Anything stored only in the activity's variables is lost.

Careful: A classic beginner bug: a counter or form text resets to zero when the phone is rotated. Keep screen state in a ViewModel (survives configuration changes) or use rememberSaveable in Compose (survives rotation and even process death for small values).

Process death

When memory is low, Android may kill your app's process while it is in the background. When the user returns, Android recreates the activity and passes a savedInstanceState Bundle. Small UI state saved with rememberSaveable or SavedStateHandle is restored; everything else must be reloaded, for example from Room.

Think of it like this: The lifecycle is like a shopkeeper's day. onCreate is setting up the shop, onStart is opening the shutter, onResume is serving customers, onPause is a short tea break with the shutter half open, onStop is closing for lunch, onDestroy is shutting the shop. A configuration change is like being told to move to the shop next door: everything not packed in the ViewModel box is left behind.

Common mistakes

  • Keeping important state in plain activity variables: lost on rotation.
  • Doing heavy work in onCreate on the main thread: slow app start. Load data with coroutines.
  • Forgetting to stop location or sensor updates in onStop, draining the battery.
  • Relying on onDestroy to save data: it may never run if the process is killed. Save earlier.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Activities and the lifecycle · 1/6

Activity = entry point

An Activity is an entry point that shows a screen. Compose apps usually have one MainActivity.

Prefer a video by a teacher? Find free videos on “android activity lifecycle explained configuration change rotation” on YouTube ↗

In real life: A video lesson app

An e-learning app plays recorded classes. When a phone call arrives, the activity goes to onPause and the video pauses; when the user returns, onResume continues it. When the student rotates the phone for full screen, the activity is recreated, but the current position is kept in a ViewModel, so the class continues from the same second instead of restarting.

kotlin
// Lifecycle-aware pattern in a Compose screen (simplified):
// val position by viewModel.position.collectAsStateWithLifecycle()
// The ViewModel survives rotation, so 'position' is not lost.
Details of ViewModel and collection come in module 7.

Practice (0/3 done)

Task 1 · Question

A counter on screen resets to 0 when the phone is rotated. Why?

Task 2 · Question

Which callback is the right place to call setContent?

Task 3 · Practice

Override onCreate, onStart, onResume, onPause, onStop and onDestroy in MainActivity, each logging its name with Log.d. Run the app, then: press Home, return, rotate the phone, and press Back. Write down the order of callbacks for each action from Logcat.

Quick quiz

Question 1

1.Which callback means the activity is in front and the user can interact?

Question 2

2.What is a configuration change?

Question 3

3.Which survives a configuration change?

Question 4

4.Is onDestroy guaranteed to run before Android kills a background process?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which callback means the activity is in front and the user can interact?

Answer: onResume

onResume marks the interactive state.

What is a configuration change?

Answer: A change like rotation, dark mode or language that recreates the activity by default

The activity is recreated to load the right resources.

Which survives a configuration change?

Answer: A ViewModel

ViewModels outlive configuration changes.

Is onDestroy guaranteed to run before Android kills a background process?

Answer: No; save important data earlier

The process may be killed without onDestroy.

Why must a ViewModel not hold an Activity reference?Related

Answer: The ViewModel outlives the activity, causing a memory leak

The activity is recreated on rotation.

From Interview questions: Android and Compose

Which survives screen rotation?Related

Answer: rememberSaveable

rememberSaveable stores the value in saved state.

From State and recomposition

What does the ViewModel expose to the UI?Related

Answer: A read-only StateFlow of UI state

Expose read-only state.

From ViewModel and MVVM

Which function shows Compose content in an activity?Related

Answer: setContent

setContent { } hosts the composables.

From Hello Compose: your first screen

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Android Studio and your first app” before its exam: Hello Compose: your first screen.
  2. Module 5 exam: Android Studio and your first app · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Jetpack Compose UI. 50 topics left in the course before the final exam.

← Previous: Project structure and Gradle