Activity lifecycle and configuration changes
Why it matters
- Every screen lives inside an Activity, and the system, not your code, decides when it is created, stopped and destroyed.
- Most "my data disappeared" bugs come from here: rotation, switching apps, low memory.
- It is the first filter in many Android interviews. A weak answer here ends the round early.
- ViewModel, saved state, Flow collection and navigation all depend on it. Learn this once and the rest makes sense.
The simple explanation
Think of a market stall. You run the stall, but the market manager decides when it is open.
- The manager can tell you to set up the stall, open it, and serve customers.
- A van can park in front for a minute. You are still there but cannot serve: paused.
- At night the stall is covered: stopped. Your goods are still inside.
- If the manager wants a different stall shape, you must tear it down and build it again. That is rotation.
- If the market needs the space, the manager can remove a covered stall without telling you. That is process death.
What you still have afterwards depends on where you kept it:
- On the counter (a field in the Activity, or
remember): gone when the stall is rebuilt. - In the storeroom next door (a
ViewModel): survives a rebuild, gone if the whole market closes your spot. - In the small notebook the manager keeps for you (saved state): comes back both times, but it only fits a few lines.
The real names:
| Callback | The Activity is now | Typical work |
|---|---|---|
onCreate | created, not visible | set content, read saved state, connect the ViewModel |
onStart | visible | start collecting UI flows |
onResume | in the foreground | start camera preview, resume animations |
onPause | still partly visible, losing focus | pause things that must not run without focus |
onStop | not visible | stop collecting, release the camera, save drafts |
onDestroy | going away | final cleanup, but do not rely on it |
The screen is launched. Type a few times, then rotate, or press Home and let the system kill the process.
- Not createdno Activity instance exists
- Created, not visiblein the background after onStop
- Resumedvisible and taking input
- Process killedthe system took the memory back
- onCreate(null)
- onStart()
- onResume()
| Where the count is kept | Value now | After the last event |
|---|---|---|
| remember { } or an Activity field | 0 | — |
| ViewModel field | 0 | — |
| rememberSaveable or SavedStateHandle | 0 | — |
Notes
- Visible is not the same as in front. Started means visible. Resumed means in the foreground. Since Android 10 several activities can be resumed at once in multi-window, and only the top one receives input.
- A configuration change destroys and recreates the Activity by default: rotation, dark mode, language, font size, window resize, folding.
onSaveInstanceStateruns afteronStopon Android 9 (API 28) and newer. On older versions it ran beforeonStop.onDestroyis not guaranteed. When the system kills the process, no callback runs at all.- A
ViewModelsurvives configuration changes. It does not survive process death. It is cleared when the screen is finished for good. - Saved state survives both, but the Bundle must stay small. Save ids and short text, not lists or images.
- Saved state does not survive the user swiping the app away from Recents, Force stop, or a reboot. Anything important goes to disk.
- In Compose:
rememberis lost on a configuration change.rememberSaveablesurvives a configuration change and process death.ViewModel+SavedStateHandleis the place for screen state that must survive both.
- Collect flows with
collectAsStateWithLifecycle()so collection stops when the screen is not visible. - Since Android 12, pressing Back on the root screen of the launcher Activity moves the app to the background. It does not finish the Activity.
Code example
A search screen. The query is small and must never be lost, so it goes in SavedStateHandle. The results are large and can be loaded again, so they stay in memory only.
@HiltViewModel
class SearchViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val repository: SearchRepository,
) : ViewModel() {
// Small UI state: survives rotation AND process death.
val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")
// Loaded data: survives rotation only.
// After process death it is loaded again from the restored query.
@OptIn(ExperimentalCoroutinesApi::class)
val results: StateFlow<List<Item>> = query
.mapLatest { repository.search(it) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
fun onQueryChange(text: String) {
savedStateHandle["query"] = text
}
}
@Composable
fun SearchScreen(viewModel: SearchViewModel = hiltViewModel()) {
// Stops collecting when the screen is not visible.
val query by viewModel.query.collectAsStateWithLifecycle()
val results by viewModel.results.collectAsStateWithLifecycle()
Column {
TextField(value = query, onValueChange = viewModel::onQueryChange)
LazyColumn {
items(results, key = { it.id }) { item -> Text(item.title) }
}
}
}Why WhileSubscribed(5_000): during rotation the UI stops collecting for a moment. The five seconds keep the search alive across that gap, so rotation does not restart the request.
This sample is kept short to show where state lives. A production version also needs:
- Error handling. If
repository.searchthrows, the exception reachesviewModelScopeand crashes the app. Catch it and show an error state. - A debounce, so a request is not sent on every keystroke.
- Compose state for the text field. Feeding a
TextFieldfrom aStateFlowcan make the cursor jump while typing fast. Keep the text inmutableStateOf(saved throughSavedStateHandle) and derive the query flow from it.
Run the idea in plain Kotlin
Android code cannot run in a browser, but the rule can. This model shows what "destroy and recreate" does to a field that was not saved.
class FakeActivity(savedState: Map<String, Int>?) {
var counter = savedState?.get("counter") ?: 0 // restored if it was saved
var notSaved = 0 // starts again from 0
fun onSaveInstanceState() = mapOf("counter" to counter)
}
fun main() {
var activity = FakeActivity(savedState = null)
activity.counter = 3
activity.notSaved = 3
// Rotation: the system saves state, drops the instance, creates a new one.
val saved = activity.onSaveInstanceState()
activity = FakeActivity(saved)
println("counter = " + activity.counter) // 3
println("notSaved = " + activity.notSaved) // 0
}In production
- Users type a delivery address, switch to their banking app for a one-time code, and return to an empty form.
- Support tickets say "the app deleted my address". Developers cannot reproduce it: their phones have plenty of memory.
- Cause: the form text lived only in ViewModel fields. On low-memory phones the system killed the process in the background. The ViewModel died with it.
- Reproduce it first. Press Home, then run
adb shell am kill com.example.app, then reopen the app from Recents. Or turn on "Don't keep activities" in Developer options. - Move small form fields to
SavedStateHandle(orrememberSaveablefor pure UI state). - For long forms, also save a draft to disk (DataStore or Room) in
onStop. - Add a test so it cannot come back:
- For ViewModel state, build the ViewModel with a restored handle, for example
SearchViewModel(SavedStateHandle(mapOf("query" to "shoes")), fakeRepository), or useViewModelScenario.recreate()fromlifecycle-viewmodel-testing. - For
rememberSaveablestate, useStateRestorationTesterin Compose tests. - Do not rely on
ActivityScenario.recreate()here. It behaves like rotation: the ViewModel survives, so the test passes while the bug is still there.
- For ViewModel state, build the ViewModel with a restored handle, for example
"Don't keep activities" destroys the Activity and its ViewModel but keeps the process alive, so singletons and in-memory caches survive. am kill is the faithful test.
- A team "fixed" lost state by putting a list of 2,000 items into saved state.
- Result:
TransactionTooLargeExceptioncrashes when the app goes to the background. - Cause: saved state travels to the system process through Binder, which has a small buffer (about 1 MB, shared by all transactions in progress).
- Save only what you need to rebuild the screen: ids, the query, the scroll position.
- Reload the heavy data from the repository or the database.
Common mistakes
- Using
rememberfor user input. The text is lost on rotation. UserememberSaveableor the ViewModel. - Keeping an Activity or View reference in a ViewModel or singleton. The old Activity cannot be freed after rotation: a memory leak.
- Adding
android:configChangesto "fix" rotation. It hides the bug. Process death still loses the state. - Cleaning up only in
onDestroy. It may never run. Release the camera, sensors and receivers inonStoporonPause. - Starting a network call in
onResume. It runs again every time the user returns, so you send duplicate requests. Load from the ViewModel instead. - Testing only on a flagship phone. Process death is rare there and common on low-memory devices.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens when the user rotates the screen?”
“What is the difference between onPause and onStop?”
“How does a ViewModel survive a configuration change?”
“How do you handle process death?”
Quiz
The user rotates the phone. Which value is lost?
The app is in the background and the system kills its process. Which callback runs at that moment?
Where should the text of a short form field live so it survives rotation and process death?
Why is saving a large list in saved state a bad idea?
0 of 4 answered
Mini task
Build one screen with three counters and one button that adds 1 to all of them:
- One counter in
remember. - One in
rememberSaveable. - One in a
ViewModelproperty.
Then do this and write down what each counter shows:
- Rotate the phone.
- Press Home, run
adb shell am kill <your.package>, and reopen the app from Recents.
You are done when you can explain each result without looking at this page.