Lesson 8 · Mobile and offline architecture
App lifecycle and state restoration
What iOS and Android do to your app in the background, and how to survive it.
About 25 minutes
Tab indents. Press Escape, then Tab, to leave the editor.
On mobile, the operating system owns your process. It suspends it the moment the user switches away, kills it when memory is tight, and recreates your UI from scratch on a rotation or a window resize, all without asking. Browsers increasingly do the same to background tabs. The user's expectation is simple: come back, and everything is where they left it. This lesson covers what iOS, Android and the web actually do to your app, which callbacks you can rely on, and where state has to live to survive each event.
iOS: scenes, states and suspension
Since iOS 13, UI lifecycle is per scene (a window; an iPad app can have several) rather than per app. Each scene moves through:
| State | What's true |
|---|---|
| Unattached | Scene not yet connected, or disconnected by the system to reclaim resources |
| Foreground inactive | On screen but not receiving events: during launch, the app switcher, an incoming call banner, Control Center |
| Foreground active | On screen and receiving events |
| Background | Off screen and still executing, briefly |
| Suspended | In memory but given no CPU time at all |
In SwiftUI you observe this through scenePhase (.active, .inactive, .background):
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup { ContentView() }
.onChange(of: scenePhase) { _, phase in
if phase == .background { store.saveNow() } // last guaranteed chance
}
}
The critical facts:
- Going to the background is your last reliable callback. You get a few seconds; if you need more to finish a write or an upload, wrap it in
UIApplication.shared.beginBackgroundTask(expirationHandler:)and end it as soon as you're done. The system decides how long you get (checkbackgroundTimeRemaining, and handle expiration). - A suspended app is killed without being woken. When memory runs low the system terminates suspended apps, and none of your code runs.
applicationWillTerminateis called only in narrow cases. Anything not saved before suspension is gone. - Background work is scheduled by the system, not by you.
BGTaskSchedulerrunsBGAppRefreshTask(short refreshes) andBGProcessingTask(longer work, optionally only on power or network) when the system chooses, based on how the user uses your app, battery and conditions, possibly never. iOS 26 addsBGContinuedProcessingTaskfor work the user started in the foreground (an export, say) that should keep going after they leave: the system shows its progress in a Live Activity, the user can cancel it, and you must report progress throughProgressReporting, because under resource pressure the system terminates the tasks making the least progress first. Uploads and downloads that must finish belong in a backgroundURLSession, which a system daemon completes while you're suspended.
State restoration
Users expect to return to the same screen, tab, scroll position and half-typed text, even after the app was killed in the background. SwiftUI gives you two tools:
@SceneStorage("key")persists small values (String,Int,Bool,URL,Data,RawRepresentable) per scene and restores them when the system recreates that scene. Use it for UI state: selected tab, navigation path (encoded), draft text. It's not a database: don't put model data in it, and expect it to be discarded if the user force-quits the app from the app switcher, which also discards the scene.NSUserActivitydescribes what the user is doing (viewing guide X) and drives Handoff, Spotlight and restoration. Publish it with.userActivity(_:)and handle it with.onContinueUserActivity(_:). In UIKit,stateRestorationActivity(for:)on the scene delegate plays this role.
@AppStorage is UserDefaults: global and persistent, right for preferences, wrong for per-window state.
Android: activities, configuration changes and process death
An Activity moves through onCreate → onStart → onResume (interactive) and back out through onPause → onStop (not visible) → onDestroy. Lifecycle-aware components (LifecycleObserver, repeatOnLifecycle, Compose's LifecycleResumeEffect) let you tie work to these states rather than overriding callbacks.
Two separate events destroy your UI, and they have different survivors:
Configuration changes. Rotation, a window resize in split screen or on a foldable, a dark-mode switch, a locale or font-scale change: by default the system destroys the Activity and creates a new one with the new configuration. On large screens this is now routine: for apps targeting Android 16 (API 36), the system ignores screenOrientation, resizeableActivity="false" and min/max aspect ratios on displays at least 600dp wide (smallest width), so you will see rotations and resizes whether you planned for them or not. Games are exempt, and a temporary opt-out (PROPERTY_COMPAT_ALLOW_RESTRICTED_RESIZABILITY) stops working once you target API 37. A ViewModel survives configuration changes, since it's retained across the recreation.
Process death. When your app is in the background and the system needs memory, it kills the whole process. When the user returns, Android restores the task: it starts a new process and recreates the Activity with its saved instance state. The ViewModel is gone (it lived in the old process). Only what you put in the saved-state Bundle comes back.
class SearchViewModel(private val state: SavedStateHandle) : ViewModel() {
// Survives configuration changes AND process death (stored in the saved-state Bundle)
val query: StateFlow<String> = state.getStateFlow("query", "")
fun onQueryChange(q: String) { state["query"] = q }
// Survives configuration changes only: reload from the repository after process death
val results = query.flatMapLatest { repo.search(it) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
}
@Composable
fun NoteEditor() {
// rememberSaveable writes to the saved-state Bundle; plain remember is lost on recreation
var draft by rememberSaveable { mutableStateOf("") }
TextField(value = draft, onValueChange = { draft = it })
}
Keep the Bundle small: ids, queries, scroll positions, short drafts. Saved state travels through a Binder transaction with a limited buffer (around 1 MB, shared by the process), and exceeding it throws TransactionTooLargeException. Persist anything larger to your database and save only its key.
To test process death: put the app in the background and run adb shell am kill <package> (it only kills background processes), then return through the launcher or recents. The developer option "Don't keep activities" destroys activities when you leave them, which tests recreation but not process death, since your process and its ViewModels survive.
Background execution on Android is also constrained (Doze, App Standby Buckets, limits on starting foreground services). Deferrable work that must eventually happen, such as draining a sync outbox, belongs in WorkManager.
The web: Page Lifecycle
Browsers apply the same pressure to tabs. Chromium's Page Lifecycle model names the states: active (visible, focused), passive (visible, not focused), hidden (not visible), frozen (hidden and suspended: no timers or tasks run; Chromium freezes some background tabs to save CPU and battery), discarded (unloaded by the browser to free memory; the tab reloads when the user returns, with document.wasDiscarded set), and terminated.
The events, and which you can trust:
visibilitychangetohiddenfires when the user switches tabs or apps, minimizes, locks the phone, or navigates away. On mobile it's the last event you can count on: after it, the page may be frozen, discarded or killed with no further events. Save state and flush analytics here (navigator.sendBeacon()orfetch(..., { keepalive: true })).pagehidefires when the page is being unloaded or put into the back/forward cache (event.persistedtells you which). Use it as a second save point.beforeunloadandunloadare unreliable on mobile (not fired when the OS kills a backgrounded browser). Anunloadhandler also makes the page ineligible for the back/forward cache in Chromium and Firefox, and Chrome is phasingunloadout. Usebeforeunloadonly to warn about unsaved changes, added while there are some and removed once saved.pageshowwithevent.persisted === truemeans the page was restored from the bfcache: the whole JS heap and DOM are as they were, including form contents, but time has passed. Refresh stale data and reopen connections.freezeandresume(Chromium) bracket the frozen state: close IndexedDB connections that would block other tabs' upgrades, and reconnect on resume.
Challenge
Never lose a draft
The note editor saves its draft on beforeunload, which mobile browsers often never fire. Fix it:
- Save the draft when the page becomes hidden (
visibilitychangewithdocument.visibilityState === 'hidden'). Apagehidelistener as a second save point is a good idea too. - Implement
restoreDraft()so it puts a saved draft back into the editor. It already runs at startup. - Make Send clear the saved draft as well as the editor.
The sandboxed preview has no localStorage, so draftStore stands in with the same getItem/setItem/removeItem API. To try it, type something, switch to another browser tab and back, and watch the status line.
- Nothing logged yet.
- The draft is saved when the page becomes hidden
- restoreDraft() brings a saved draft back into the editor
- Sending clears both the editor and the saved draft
In a real app you'd also save on a debounce while typing (a few hundred milliseconds after the last keystroke), so a crash or a killed browser loses seconds of work rather than a whole session, and you'd store a timestamp with the draft so a stale draft from last week doesn't silently replace newer server content.
One model for every platform
The three platforms converge on the same rules:
- Persist continuously, and at the last reliable signal:
scenePhase == .backgroundon iOS,onStop(and saved state) on Android,visibilitychangeto hidden on the web. Never rely on a termination callback. - Separate UI state from model data. UI state (selected tab, scroll position, draft text, navigation path) goes in the platform's restoration mechanism:
@SceneStorage/NSUserActivity,SavedStateHandle/rememberSaveable, or your own storage keyed per view on the web. Model data goes in your database, written as changes happen. - Make startup a restore. Cold start after process death should look exactly like returning to a suspended app. Test it deliberately:
adb shell am kill, stopping the app from Xcode while it's in the background (which simulates termination without the force-quit that discards restoration state), andchrome://discardsto discard a tab. - Treat background execution as opportunistic. WorkManager,
BGTaskScheduler, backgroundURLSessionand Background Sync can speed things up, but correctness must not depend on them.
Recap
- iOS suspends apps on leaving the foreground and kills suspended apps without running code; save on the
.backgroundphase and restore UI state with@SceneStorageandNSUserActivity. - Android recreates activities on configuration changes (
ViewModelsurvives) and kills processes in the background (only saved state survives:SavedStateHandle,rememberSaveable, kept small). - On the web,
visibilitychangeto hidden is the last reliable event; usepagehideas a second save point, avoidunload, and handle bfcache restores viapageshow. - Design every platform the same way: persist continuously, separate UI state from model data, and make cold start indistinguishable from resume.
Finished this lesson?
Mark it complete to track your progress on this device.