Activity lifecycle and configuration changes

What the system does to your screen on rotation, backgrounding and process death, and which state survives each one. About 25 minutes.

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:

CallbackThe Activity is nowTypical work
onCreatecreated, not visibleset content, read saved state, connect the ViewModel
onStartvisiblestart collecting UI flows
onResumein the foregroundstart camera preview, resume animations
onPausestill partly visible, losing focuspause things that must not run without focus
onStopnot visiblestop collecting, release the camera, save drafts
onDestroygoing awayfinal cleanup, but do not rely on it
Try it: what survives?

The screen is launched. Type a few times, then rotate, or press Home and let the system kill the process.

  1. Not createdno Activity instance exists
  2. Created, not visiblein the background after onStop
  3. Resumedvisible and taking input
  4. Process killedthe system took the memory back
Callbacks, in order
  1. onCreate(null)
  2. onStart()
  3. onResume()
Where the count is keptValue nowAfter the last event
remember { } or an Activity field0—
ViewModel field0—
rememberSaveable or SavedStateHandle0—
What rotation does to your screen
What rotation does to your screen On rotation the system calls onPause, onStop and onDestroy on the old Activity, and its fields and remember values are lost. The ViewModel is kept. The system creates a new Activity: onCreate reads the saved state and connects to the same ViewModel, then onStart and onResume follow. The user rotates the phone Fields and remember values are gone Kept, not cleared onPause, onStop onDestroy onCreate(savedState) SAME VIEWMODEL onStart, onResume System Android framework Old Activity before rotation ViewModel ViewModelStore New Activity after rotation
The Activity is torn down and built again, but the ViewModel is kept and the new Activity connects to the same one.

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.
  • onSaveInstanceState runs after onStop on Android 9 (API 28) and newer. On older versions it ran before onStop.
  • onDestroy is not guaranteed. When the system kills the process, no callback runs at all.
  • A ViewModel survives 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:
    • remember is lost on a configuration change.
    • rememberSaveable survives a configuration change and process death.
    • ViewModel + SavedStateHandle is 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.search throws, the exception reaches viewModelScope and 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 TextField from a StateFlow can make the cursor jump while typing fast. Keep the text in mutableStateOf (saved through SavedStateHandle) 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

The checkout form that forgot the address
  • 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.
The fix
  1. 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.
  2. Move small form fields to SavedStateHandle (or rememberSaveable for pure UI state).
  3. For long forms, also save a draft to disk (DataStore or Room) in onStop.
  4. 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 use ViewModelScenario.recreate() from lifecycle-viewmodel-testing.
    • For rememberSaveable state, use StateRestorationTester in 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.

"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.

The crash after saving too much
  • A team "fixed" lost state by putting a list of 2,000 items into saved state.
  • Result: TransactionTooLargeException crashes 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).
The fix
  • 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 remember for user input. The text is lost on rotation. Use rememberSaveable or 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:configChanges to "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 in onStop or onPause.
  • 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:

  1. One counter in remember.
  2. One in rememberSaveable.
  3. One in a ViewModel property.

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.

Next: Fragments and their lifecycle