MB·01
Platforms, Lifecycle and the Main Thread
What makes mobile different from every other platform in these volumes: a small, battery-powered computer that the operating system can pause or kill at any moment, on networks that come and go; Android's processes, activities, configuration changes and process death, iOS's app and scene states, background limits on both, the single UI thread and its frame budget at 60 and 120 Hz, permissions and sandboxes, and app-store distribution; with a lab that parses a large response on the UI thread and on a worker thread and counts dropped frames.
Start here: a computer that can vanish
A web page lives in a browser tab; a server lives in a data centre with power and a network. A mobile app lives on a device the user carries into lifts and onto trains, that runs on a battery, and whose operating system freely pauses and kills apps to save memory and power. Everything in mobile engineering follows from four constraints:
| Constraint | Consequence |
|---|---|
| the OS controls your process | save state continuously; expect to be killed in the background and restored later |
| one UI thread draws everything | keep it free; every heavy job goes elsewhere, or the app stutters and freezes |
| networks are slow, lossy and intermittent | design offline-first, batch requests, survive disconnection (chapters 04–05) |
| battery and memory are scarce | limit background work, radio use and image memory (chapters 06–07) |
And one more that changes how you ship: apps are installed copies. You can't redeploy them like a server; users update when they choose, so old versions run for months (chapter 09).
The main thread, measured
The lab ran a "UI thread" that must produce a frame every 16.7 ms (60 Hz) or 8.3 ms (120 Hz), spending 35% of each frame on normal UI work. Twice a second the app parsed an 8 MB JSON response (~40 ms here; a mid-range phone is slower):
| Refresh rate | Parse on… | Frames missed | Worst gap between frames |
|---|---|---|---|
| 60 Hz | the UI thread | 7.3% | 53 ms |
| 60 Hz | a worker thread | 0% | 18.5 ms |
| 120 Hz | the UI thread | 6.6% | 62.5 ms |
| 120 Hz | a worker thread | 0.2% | 12.8 ms |
Moving one parse off the UI thread removed nearly all dropped frames. At 120 Hz the budget is only 8.3 ms, so work that was "almost fine" at 60 Hz becomes visible stutter.
How deep to go
Volume 17 defines six mastery levels. For platforms and lifecycle:
| Level | What you can do |
|---|---|
| L1 | Describe the app lifecycle and the main-thread rule |
| L2 | Build screens that keep state across rotation and backgrounding |
| L3 | Explain process death, configuration changes, background limits and frame budgets |
| L4 | Find the cause of jank, ANRs, lost state and background kills from traces |
| L5 | Design an app's architecture around lifecycle and threading constraints |
| L6 | Run it across thousands of device models and OS versions in production |
The platforms
| Android | iOS / iPadOS | |
|---|---|---|
| current major release (Nov 2026) | Android 17 (released mid-2026) | iOS 27 (September 2026) |
| languages | Kotlin (Java legacy) | Swift (Objective-C legacy) |
| modern UI toolkit | Jetpack Compose | SwiftUI |
| devices | thousands of models, many manufacturers, wide price range | a few dozen models, one manufacturer |
| update adoption | slow and uneven (manufacturer and carrier dependent) | fast (most devices on the latest major within months) |
| distribution | Google Play, other stores, direct install | App Store (plus alternative distribution where regulation requires it) |
In India, Android has the large majority of users, with many mid-range and low-end devices: performance and data usage on a ₹10,000 phone on a congested network is the real test, not the developer's flagship.
Android's lifecycle
- An app runs in a Linux process started on demand; it contains activities (screens or, in modern apps, one activity hosting a Compose navigation graph), services, broadcast receivers and content providers.
- An activity moves through
created → started (visible) → resumed (in focus) → paused → stopped → destroyed. Lifecycle-aware components observe these states so work stops when the screen isn't visible. - Configuration changes destroy and recreate the activity. Keep screen state in a
ViewModel(survives recreation) and inSavedStateHandle(survives process death). - Process death: in the background, the process can be killed at any time. Test it: put the app in the background and run
adb shell am kill <package>, then return. - Background limits: background services are restricted; scheduled work goes through WorkManager (respects battery and network constraints); user-visible ongoing work (a delivery tracking session, a download) uses a foreground service with a notification and a declared type.
iOS's lifecycle
- App states: not running → inactive → active (foreground), background (briefly, for finishing work), suspended (in memory, not running), then possibly terminated without notification when memory is needed.
- Scenes (one per window on iPad) have their own lifecycle; SwiftUI exposes
scenePhase(active, inactive, background). - On entering the background, save state quickly; long work needs background tasks (
BGTaskSchedulerfor deferrable processing and refreshes, scheduled at the system's discretion), background URL sessions for transfers, or specific modes (audio, location, VoIP). - State restoration (
@SceneStorage,NSUserActivity) brings users back to where they were after termination.
The main thread and frames
Both platforms render the UI from one main thread, and redraw at the display's refresh rate (60, 90 or 120 Hz). Each frame the main thread must handle input, run UI code, measure and lay out, and record drawing commands, then hand off to a render thread and the GPU, all within the frame budget (16.7 ms at 60 Hz, 8.3 ms at 120 Hz). Miss it and the frame is dropped: jank.
Keep off the main thread:
- network calls (both platforms forbid or warn about them), disk and database I/O, JSON parsing of large payloads (the lab), image decoding (chapter 06), heavy computations.
Tools: Android's StrictMode (flags disk and network on the main thread), Perfetto / Android Studio profiler traces, JankStats; iOS's Instruments (Time Profiler, Hangs, Animation Hitches), and the main thread checker.
Permissions and the sandbox
- Each app has private storage; access to photos, location, contacts, camera, microphone, notifications and Bluetooth needs runtime permission, asked in context ("allow location so we can find kitchens near you") and handled gracefully when denied.
- Ask for the least precise permission that works (approximate location, the photo picker instead of full library access, location only while using the app).
- Declare why in the store listing and privacy labels; reviewers check.
Distribution
Apps reach users through stores with review, signing and staged rollouts, which shapes everything about release engineering (chapter 09): you can't hotfix the client in minutes, so risky behaviour sits behind server-controlled flags.
Common traps
- State only in memory, lost on process death.
- Work tied to an activity or view that's destroyed on rotation.
- I/O or parsing on the main thread.
- Testing only on a flagship phone on office Wi-Fi.
- Asking for every permission at first launch.
Lab: the frame budget
Setup. Node.js 22 on the lab machine, standing in for an app's UI runtime (a single event loop, like a UI thread) with worker_threads standing in for background threads. A "frame" timer fires every 16.7 ms (60 Hz) or 8.3 ms (120 Hz) and spends 35% of the budget on normal UI work. Every 500 ms the app parses an 8.4 MB JSON response of 100,000 dishes (~40 ms per parse on this server CPU; a mid-range phone takes longer), either on the UI thread or by posting it to a worker. A frame is counted as missed when the gap since the previous frame exceeds 1.5× the budget (each whole budget elapsed counts as one missed frame). Each run lasts 5 s.
Results
| Refresh rate | Parse runs on | Frames drawn | Frames missed | Worst gap |
|---|---|---|---|---|
| 60 Hz | UI thread | 292 | 23 (7.3%) | 53.0 ms |
| 60 Hz | worker thread | 309 | 0 (0.0%) | 18.5 ms |
| 120 Hz | UI thread | 577 | 41 (6.6%) | 62.5 ms |
| 120 Hz | worker thread | 615 | 1 (0.2%) | 12.8 ms |
What it shows
- One heavy job on the UI thread drops several frames at once: a 40 ms parse spans 2–3 frames at 60 Hz and ~5 at 120 Hz. Users perceive stutter during scrolling or animations even if the average frame rate looks fine.
- Offloading fixes it completely, as long as the result is handed back as a small message (here, the parsed count; in an app, a ready-to-render list).
- Higher refresh rates raise the bar. Normal UI work took 35% of the budget at both rates, but the same background interruption hurt more frames at 120 Hz.
- On real devices, add garbage collection, slower CPUs and thermal throttling: measure with Perfetto, Android Studio's profiler or Instruments on a mid-range phone.
Try it yourself
- Halve the parse size and find the largest parse that drops no frames at 60 Hz and at 120 Hz.
- Make the worker return the full parsed object (structured clone) and measure the cost of sending it back to the UI thread.
- Stream-parse the response in chunks on the UI thread, yielding between chunks, and compare with the worker.
- In an Android app, enable StrictMode and parse a large asset on the main thread; read the violation and the Perfetto trace.
Revision sheet: platforms, lifecycle and the main thread
Key ideas
- The OS controls your process; one UI thread draws everything; networks and batteries are unreliable and scarce; shipped versions live on.
- Android: activities, configuration changes, ViewModel vs SavedStateHandle, process death, WorkManager, foreground services.
- iOS: active, inactive, background, suspended, terminated; scenes; BGTaskScheduler; state restoration.
- Frame budgets: 16.7 ms at 60 Hz, 8.3 ms at 120 Hz; keep I/O, parsing, decoding and computation off the main thread.
- Runtime permissions in context, least precise; private sandboxed storage.
Numbers to remember
- Lab: 40 ms parse on the UI thread → ~7% of frames missed, worst gap 53–63 ms; on a worker → ~0%.
- ANR after ~5 s of unhandled input on Android.
Glossary
- Process death: the OS killing a backgrounded app's process.
- Configuration change: rotation, locale, theme or size change that recreates Android activities.
- Jank: visible stutter from missed frames.
- ANR: Application Not Responding.
- Foreground service: Android work the user is aware of, with a notification.