androidengineers.Book a session

Architecture & Data

Activity Lifecycle

article20 minMedium

An Activity is a screen-level Android component. The Activity lifecycle is the sequence of callbacks Android sends as the screen is created, shown, paused, stopped, and destroyed.

Understanding lifecycle prevents crashes, lost state, and wasted work.

Core Callbacks

The common flow is:

onCreate -> onStart -> onResume -> running
onPause -> onStop -> onDestroy

onCreate is where you initialize the screen.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        App()
    }
}

onStart means the Activity is visible. onResume means the user can interact with it. onPause means another screen is partially covering it. onStop means it is no longer visible.

Configuration Changes

When the device rotates, Android may recreate the Activity.

onPause -> onStop -> onDestroy -> onCreate -> onStart -> onResume

Do not store important screen data only in Activity fields. Use a ViewModel for screen state that should survive configuration changes.

Saving Small UI State

For small values, use rememberSaveable in Compose.

var text by rememberSaveable { mutableStateOf("") }

This is useful for form text, selected tabs, and scroll-related UI values.

Process Death

When Android is low on memory, it can kill your app's process entirely. When the user navigates back, Android recreates the app from scratch.

This is different from rotation. With rotation, the ViewModel survives. With process death, the ViewModel is gone too.

To preserve small values across process death, use rememberSaveable in Compose or SavedStateHandle in the ViewModel:

class TaskViewModel(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    var searchQuery by savedStateHandle.saveable { mutableStateOf("") }
        private set
}

SavedStateHandle writes small values to the saved instance state bundle, which Android preserves across process death. Use it for things like selected IDs, search text, and scroll position.

Common Beginner Mistakes

MistakeFix
Loading data directly every time onCreate runsLet ViewModel own loading
Assuming onDestroy always means app is closingIt may be rotation
Keeping long-running work in ActivityUse lifecycle-aware APIs
Forgetting state restorationUse ViewModel and saved state

Practice

Add logs to each lifecycle callback in a sample Activity. Rotate the device and observe the callback order in Logcat.

Summary

The Activity lifecycle is Android's way of managing screen visibility and resources. Junior developers should know the callback order, configuration changes, process death, and why ViewModels plus SavedStateHandle are the complete answer for state preservation.

YOUR LEARNING JOURNEY

0 of 22 available lessons completed

Progress saved in this browser. No account needed.
Activity Lifecycle | Junior Android Developer | Android Engineers