Activity lifecycle & configuration changes
An Activity passes through 6 core callbacks:
- onCreate — once: UI is built, state restored.
- onStart — the screen becomes visible.
- onResume — user interaction begins (foreground).
- onPause — focus is lost (a dialog/another activity appears on top). Must be quick.
- onStop — fully invisible. Release resources here.
- onDestroy — the activity is destroyed: finish(), a configuration change, or the system killing the process.
A configuration change (rotation, locale, dark mode) by default destroys and recreates the activity. Three mechanisms guard against data loss: ViewModel (objects; survives config changes), onSaveInstanceState (small primitives; also survives process death), SavedStateHandle (the union of both, inside the ViewModel).
| Scenario | Callbacks invoked |
|---|---|
| First launch | onCreate → onStart → onResume |
| Home button | onPause → onStop (returning: onRestart → onStart → onResume) |
| A translucent dialog-activity on top | Only onPause (still visible) |
| Rotation | onPause → onStop → onDestroy → onCreate → onStart → onResume |
| Back button (finish) | onPause → onStop → onDestroy |
The most common trap question: "when is onSaveInstanceState called and how does it differ from ViewModel?" A ViewModel survives config changes but not process death; onSaveInstanceState (and SavedStateHandle) survive both, but only fit small serializable data. Large data → ViewModel/repository; critical UI state (typed text, selected tab) → SavedStateHandle.
🛠 Practice task
Add a Log.d to every lifecycle callback of an Activity, then watch logcat through these scenarios:
- Launch, Home button, returning, rotation, back button.
- Turn on Developer options → "Don't keep activities" to simulate process death.
- Type into an
EditTextand check whether it survives rotation; then persist it withSavedStateHandle.
Done when: you wrote each scenario's callback order on paper and matched it against logcat.
📚 Sources and documentation
- The activity lifecycleofficialdeveloper.android.com
- Save UI statesofficialdeveloper.android.com
- Handle configuration changesofficialdeveloper.android.com