The idea: the system calls your activity

An Android screen is an activity. Your code never decides when it starts or stops. The system does, and it tells the activity by calling its lifecycle callbacks. There are six core ones: onCreate(), onStart() and onResume() on the way in, onPause(), onStop() and onDestroy() on the way out. onRestart() comes before onStart() when a stopped activity comes back.

The six callbacks in a column: onCreate, onStart, onResume, then the activity is running, then onPause, onStop, onDestroy. An arrow from onStop goes back through onRestart to onStart. A side box after onStop is onSaveInstanceState. Another arrow from the stopped state says process killed, no callback, and leads back to onCreate with a Bundle.
In: onCreate, onStart, onResume. Out: onPause, onStop, onDestroy. A stopped activity comes back through onRestart, or, if its process was killed, through a new onCreate(Bundle).

The canvas has four parts. The phone shows the screen and three tap counters. The diagram lights the callback that is running. system_server (the ActivityTaskManager) keeps the task: a back stack of activity records, each with its state and its last saved Bundle. The app process holds the real activity objects and the ViewModelStore. Each callback flies from the record to the object.

Visible, in front, stopped

AfterStateWhat it means
onCreate()createdThe object exists. Set the layout, make the ViewModel, read the saved Bundle.
onStart()startedVisible, but not yet taking input.
onResume()resumedIn front, has the focus, gets touches.
onPause()pausedLost the focus. Maybe still partly visible. Keep it short.
onStop()stoppedNot visible. The object is still in memory.
onDestroy()destroyedFinished, or about to be made again after a configuration change.

A cold start is onCreate(null), onStart(), onResume(). The null means there is no saved state yet.

Home and an incoming call

Home and a full-screen call do the same thing to the app. Another screen covers it, so it is stopped: onPause(), onStop(), onSaveInstanceState(). On Android 9 (API 28) and later, onSaveInstanceState() runs after onStop(); before that it ran before onStop(). The object is not destroyed. When the user comes back, the same object gets onRestart(), onStart(), onResume(), and every counter is still there (Demo 1: launch, Home, come back; Demo 3: an incoming call).

Back on the root activity of the launcher's task is the same as Home since Android 12: the task moves to the background and the activity is not finished. A screen that only partly covers yours, such as a permission dialog, only pauses it: onPause(), then onResume() when it goes away. An AlertDialog shown by your own activity calls no callback at all.

Rotation: destroyed and made again

Turning the device changes the configuration (orientation, screen size). By default the system destroys the activity object and makes a new one, so the new layout can load. The order is onPause, onStop, onSaveInstanceState, onDestroy on the old object, then onCreate(Bundle), onStart, onRestoreInstanceState, onResume on the new one (Demo 2: rotation loses the field).

The page counts taps three ways. After three taps and one rotation:

  • A plain field (private int taps) is 0. It lived in the old object.
  • The ViewModel (MainViewModel.taps) is still 3. In onDestroy(), isChangingConfigurations() is true, so the ViewModelStore is handed to the new object, and ViewModelProvider returns the same ViewModel.
  • The saved state (savedTaps) is 3. It was written with outState.putInt("taps", 3) and read back in onCreate(savedInstanceState).

The back stack

A task is the stack of activities the user moved through. startActivity() pushes a new one on top; Back pops the top one and finishes it. The two activities' callbacks interleave in a fixed order: the new one cannot start until the old one has paused, and the old one stops only once the new one covers it (Demo 4: back stack).

Two time-down columns, Main and Detail. Open detail: Main onPause, Detail onCreate onStart onResume, Main onStop onSaveInstanceState; back stack Detail over Main. Back: Detail onPause, Main onRestart onStart onResume, Detail onStop onDestroy; back stack Main.
Opening Detail and pressing Back: each side's callbacks wait for the other, so the screen is never empty.

Keep onPause() short. The next activity waits for it before it can start.

Process death

A stopped app can be killed at any time to free memory. No callback runs, not even onDestroy(). The objects, their fields and the ViewModel die with the process. The records and Bundles live in system_server, so they survive. When the user comes back, the system starts a new process (pid 4121 → 4387) and makes the top activity again with onCreate(Bundle). After two taps: field 0, ViewModel 0, saved 2 (Demo 5: process death).

Only the top activity is made again. An activity below it stays a record with a Bundle until Back reaches it; then it gets its own onCreate(Bundle) (Demo 6: process death with two activities). To the user it looks as if the app never stopped, if the app saved its state.

What survives what

A grid. Rows: field, ViewModel, saved instance state Bundle. Columns: Home and back, rotation, process death, Back finishes the activity. Field: kept, lost, lost, lost. ViewModel: kept, kept, lost, lost (cleared). Bundle: kept, kept, kept, lost.
Use a ViewModel for data that must outlive rotation and the Bundle for small state that must outlive process death.
Where the counter livesHome, callRotationProcess deathBack (finish)
field in the activity✓ kept✗ lost✗ lost✗ lost
ViewModel✓ kept✓ kept✗ lost✗ cleared
saved instance state (Bundle)✓ kept✓ kept✓ kept✗ thrown away

The Bundle is small and goes through a system call, so keep it to IDs and a few values. Anything bigger belongs in a database, with the ID in the Bundle.

See also A Linux Process from fork() to Reaping for the process underneath an app, The State Pattern and Finite State Machines for state machines in code and hardware, and MVC vs MVVM for where a ViewModel sits in an app.

What the page leaves out

Fragments have their own, longer lifecycle inside the activity's. Jetpack LifecycleObserver and repeatOnLifecycle let other classes react to these callbacks; SavedStateHandle lets a ViewModel itself survive process death. Views with an ID save their own state (text, scroll position) in the Bundle. An app can opt out of rotation restarts with android:configChanges and get onConfigurationChanged() instead. Multi-window mode, picture-in-picture, launch modes (singleTop, singleTask), intent flags and swiping the app away from Recents are left out; the page also rotates only while MainActivity is in front.

On the mind map

Open the Distributed Systems mind mapDistributedSystemsReplication: copies of data · what reads seeReplicationPartitioning: split data over nodesPartitioningTime and membership: order events, know who is aliveTime and membershipConsensus: agree on one value or logConsensusTransactions: one change across many servicesTransactionsMessaging: send events between systemsMessagingKafka internals: a replicated append-only logKafka internalsRedis internals: one thread, data in memoryRedis internalsKubernetes: reconcile desired stateKubernetesResilience and speed: stay up and fast under loadResilience and speedCluster architectureCluster architectureapiserver, etcd, scheduler, kubeletsPod lifecyclePod lifecycleschedule, pull, probes, terminateAndroid Activity LifecycleRotation kills fields; Bundle beats deathContainer runtimeContainer runtimekubelet to containerd over CRI gRPCLifecycle hooksLifecycle hookspreStop runs before SIGTERMControl plane and nodesControl plane and nodeshub and spoke via the API serverKubernetes schedulerKubernetes schedulerfilter nodes, score them, then bindHPA and Cluster AutoscalerHPA and Cluster Autoscalerceil(replicas x usage / target)Config and secretsConfig and secretsHelm, Argo CD, ESO feed Spring BootService discoveryService discoveryRegister on start, look up by nameOpen the Distributed Systems mind mapDistributed Systemsreconcile desired stateKubernetesCluster architectureCluster architectureapiserver, etcd, scheduler, kubeletsPod lifecyclePod lifecycleschedule, pull, probes, terminateAndroid Activity LifecycleRotation kills fields; Bundle beats deathContainer runtimeContainer runtimekubelet to containerd over CRI gRPCLifecycle hooksLifecycle hookspreStop runs before SIGTERMControl plane and nodesControl plane and nodeshub and spoke via the API serverKubernetes schedulerKubernetes schedulerfilter nodes, score them, then bindHPA and Cluster AutoscalerHPA and Cluster Autoscalerceil(replicas x usage / target)Config and secretsConfig and secretsHelm, Argo CD, ESO feed Spring BootService discoveryService discoveryRegister on start, look up by name
This page on the Distributed Systems mind map · 89 pages in 10 branches · open it to see the whole map and test yourself in recall mode.