How native Android actually works.

An Android app is a guest in a Linux process that the system can pause, recreate or kill whenever it likes. Almost everything that makes native Android feel difficult follows from that one fact. This essay works up from the kernel to the pixel: every component, lifecycle, thread and library a native app is built from, why each one exists, and how they connect.

00Concept map

Every part, and how it connects.

The map holds 177 concepts in 20 groups. Each line is a relationship you can read as a sentence: Zygote forks the process for Application, ViewModel exposes StateFlow. Pick a group to zoom in, drag to move around, and select any concept to see what it is, what it connects to, and where this essay explains it.

Pick a group above, or drag to explore.

  • System and native
  • Build and quality
  • Components and lifecycle
  • UI and the main thread
  • Coroutines and Flow
  • Architecture and data

01System · Kernel, Binder, Zygote, ART

The platform underneath.

Android is a stack. At the bottom is a Linux kernel with Android additions. Above it sit the hardware abstraction layer (HAL), where vendors plug in drivers for the camera, sensors and audio behind stable interfaces; native libraries such as SQLite, Skia and the media codecs; the Android Runtime (ART); and the Java API framework, the android.* classes your code calls. Your app sits on top of all of it.

One app, one Linux user

When an app is installed, the system gives it its own Linux user ID. Its process runs as that user, its private files belong to that user, and the kernel stops any other app from reading them. This is the app sandbox, and it is enforced twice: by ordinary Unix file permissions and by SELinux, a mandatory access control layer that confines every process, including system ones, to what its policy allows. Permissions, covered in chapter 19, are the controlled holes in that sandbox.

Zygote: every app starts as a copy

Starting a Java-style runtime from nothing is slow: load the runtime, load thousands of framework classes, load common resources. Android does that work once, at boot, in a process called Zygote. When an app needs to start, Zygote calls fork(). The child process inherits a runtime that is already warm, with framework classes and resources already in memory. The memory pages are shared copy-on-write, so ten apps share one copy of the framework until one of them writes to a page.

The forked child then specialises itself: it switches to the app's user ID, applies its SELinux context, loads the app's code and calls ActivityThread.main(). That method prepares the main thread's Looper (chapter 8) and enters a loop that never returns while the process lives.

system_server and Binder

Most of what feels like Android is not in your process at all. It is in system_server, one process hosting dozens of services: ActivityManagerService and ActivityTaskManagerService (processes, tasks and activities), WindowManagerService (windows and their z-order), PackageManagerService (installed apps), InputManagerService (touches and keys), and many more.

Your app talks to them through Binder, a kernel driver for inter-process calls. A call such as startActivity() becomes a Binder transaction: the arguments are flattened into a Parcel, the kernel copies it once into the receiving process's memory, a thread in system_server runs the method, and the reply comes back the same way. Calls the other direction work identically: when the system wants your activity to pause, it sends a transaction to your process's ApplicationThread, which posts a message to your main thread.

Binder has a fixed transaction buffer of about 1 MB per process, shared by every transaction in flight. Anything sent across it, including an Intent's extras and an activity's saved state, must be small. Exceed it and the app crashes with TransactionTooLargeException.

ART: the runtime

Your Kotlin compiles to JVM bytecode, which the build converts to DEX (Dalvik Executable), a compact register-based format. ART runs DEX in three ways at once. An interpreter runs code that has never been compiled. A JIT compiler compiles methods that turn out to be hot while the app runs, and records them in a profile. While the device is idle and charging, a background job runs dex2oat with that profile and compiles the hot methods ahead of time into machine code stored on disk. The next launch runs that machine code directly. Baseline Profiles, in chapter 21, let you ship that profile with the app so the first launch benefits too.

ART also owns the garbage collector, a concurrent copying collector that does most of its work on background threads, so pauses on your threads are short. Since Android 12, ART itself can be updated through Google Play as a Mainline module, without a full system update.

Processes are disposable

The system ranks every process by importance: foreground (the activity the user is touching), visible, perceptible (a foreground service), service, and cached (nothing the user can see). When memory runs short, the low memory killer daemon (lmkd) kills processes from the bottom of that list. A cached app is killed with no warning and no callback.

RememberYour process is borrowed. It was forked from Zygote, it talks to the system over Binder, and it can be killed at any moment it is not in the foreground. Every lifecycle, saved state and background rule in this essay exists because of that.

02Build · Kotlin, Gradle, R8, App Bundles

From source files to a signed bundle.

Google made Kotlin the preferred language for Android in 2019, and today nearly all new Android code, and every Jetpack library's public surface, is written for it. Java still runs, and the two interoperate in the same module. Kotlin's features map onto Android problems directly: null safety for the platform's many nullable returns, sealed interfaces for screen states, data classes for immutable models, extension functions for wrapping awkward APIs, and coroutines, which chapter 12 covers, for asynchronous work. Since Kotlin 2.0, the K2 compiler is the default.

Gradle and the Android Gradle Plugin

The build is run by Gradle. A Gradle build has three phases. Initialisation reads settings.gradle.kts to find which modules exist. Configuration runs every module's build script to create a graph of tasks. Execution runs the tasks the requested one depends on, skipping any whose inputs and outputs have not changed. The build cache and the configuration cache let Gradle reuse that work between builds and machines.

The Android Gradle Plugin (AGP) adds the Android-specific tasks. For one build, they do roughly this:

  1. Merge manifests. Your AndroidManifest.xml is merged with every library's manifest into one, with placeholders filled in.
  2. Compile resources. AAPT2 compiles every layout, string and drawable, links them, gives each a numeric ID, and generates the R class that names those IDs in code.
  3. Generate code. Annotation processors run through KSP (Kotlin Symbol Processing): Room writes your database code, Hilt writes your dependency graph. KSP replaced the older and slower kapt.
  4. Compile. The Kotlin and Java compilers produce JVM bytecode.
  5. Dex, shrink and optimise. In debug builds, D8 converts bytecode to DEX. In release builds, R8 does that and more (below).
  6. Package and sign. DEX files, resources, native libraries and assets are zipped into an APK or App Bundle and signed.

Build variants

A build type describes how the app is built: debug is debuggable and unoptimised, release is shrunk and signed with a release key. A product flavour describes which app is built: free and paid, or staging and production. A build variant is one combination, such as stagingRelease, and each variant can have its own source sets, resources and dependencies.

Three SDK numbers

minSdk
The oldest Android version the app installs on. Calls to newer APIs need a version check.
compileSdk
The API level your code compiles against. It decides which APIs you can call, and changes nothing at run time.
targetSdk
The version whose behaviour you have tested against. Android keeps old behaviour for apps with a lower target, so raising it switches on every behaviour change since. This is the number that breaks things.

R8

R8 is the release compiler. It shrinks by tracing what is reachable from your entry points (the components in the manifest, plus anything a keep rule names) and deleting the rest, including unused code inside libraries. It optimises by inlining, removing dead branches and merging classes. It obfuscates by renaming classes and methods to short names, and writes a mapping file so crash stack traces can be translated back. Since AGP 8, R8 runs in full mode by default, which is more aggressive. Anything reached only through reflection, such as some serialisation libraries, needs a keep rule, or R8 will remove or rename it and the app will crash in release only.

Modules

Large apps split into many Gradle modules: an app module that assembles everything, feature modules for each area, and core modules for shared data, design and utilities. Modules build in parallel, rebuild only when they change, and make dependency rules physical: a feature module that does not depend on another simply cannot reference its classes. Shared build logic lives in convention plugins, and versions in a version catalogue, libs.versions.toml.

APKs and App Bundles

An APK is the installable file. An Android App Bundle (.aab) is what you upload to Google Play, which has required it for new apps since 2021. Play splits the bundle and generates APKs for each device, with only the screen density, CPU architecture and languages that device needs. Because Play builds the final APKs, it must also sign them: with Play App Signing, Google holds the app signing key and you sign uploads with a separate upload key, which can be reset if it is lost.

RememberTest release builds, not only debug ones. R8, resource shrinking and the release signing key only apply in release, and so do the bugs they cause.

03Components · Activity, Service, Receiver, Provider

Four ways in.

An Android app has no main() function that you write. Instead it declares components in its manifest, and the system creates them when they are needed. There are four kinds, and each is an entry point the system can use to start your process.

Activity
One screen the user interacts with. The launcher icon starts one; so can a notification, a link or another app.
Service
Work with no screen. It can be started (run until stopped), bound (clients connect and call it) or foreground (visible to the user through a notification).
BroadcastReceiver
Code that runs in response to a broadcast: the device finished booting, the time zone changed, another app announced something.
ContentProvider
Structured data shared with other apps through content:// URIs. The system's contacts and media are providers.

Because the system creates these objects, you never call their constructors, and they must be declared in AndroidManifest.xml. A component that other apps may start must also say so with android:exported="true"; since Android 12 any component with an intent filter must state this explicitly.

Intents

Components are started with an Intent, a message describing an operation. An explicit intent names the exact class to start, and is how you move between your own screens. An implicit intent describes an action and some data, such as ACTION_VIEW on an https:// URL, and the system finds components whose intent filters match. If several match, the user picks.

Intents carry extras, a Bundle of small values. Extras cross Binder, so pass an ID and let the next screen load the object, rather than passing the object itself.

Since Android 11, apps cannot see most other installed apps by default. If you query for apps that can handle an intent, you must declare what you are looking for in a <queries> element in the manifest.

PendingIntent

A PendingIntent is an intent wrapped in a token you hand to another process, so that it can fire the intent later with your app's identity and permissions. Tapping a notification, an alarm going off and a home-screen widget button all fire PendingIntents. Since Android 12 you must declare whether one is mutable or immutable; make it immutable unless another app must fill in data.

Deep links and App Links

A deep link is an intent filter for a URL, so a link opens a specific screen. Any app can claim any URL this way, so Android shows a chooser. An App Link is a deep link with android:autoVerify="true" whose domain publishes a /.well-known/assetlinks.json file naming your app's signing certificate. Once verified, the link opens your app directly.

Broadcasts in practice

Receivers declared in the manifest used to wake apps for almost any system event, which drained batteries. Since Android 8, most implicit broadcasts are no longer delivered to manifest receivers; you register for them in code, with registerReceiver(), while your app is running. Since Android 14, those registrations must say whether other apps may send to them (RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED). A receiver's onReceive() runs on the main thread and must finish in about ten seconds; longer work goes to WorkManager.

RememberThe manifest is the contract with the system. If a component is not declared there, the system cannot start it; if it is exported, any app can.

04Components · Context and Application

The handle to everything.

Nearly every Android API wants a Context. It is your app's handle to its environment: resources and the theme, private files and databases, system services (getSystemService()), starting activities and services, sending broadcasts. Activities, services and the Application are all Contexts, through a class hierarchy of ContextWrappers around one real implementation, ContextImpl.

Which Context

Application context
Lives as long as the process. Right for anything long-lived: a database, an HTTP client, a singleton. It carries no activity theme and cannot show a dialog.
Activity context
Lives as long as one activity instance. It carries the theme and window, so inflating views and showing dialogs need it.

The classic Android memory leak: a long-lived object holds an activity's context. When the screen rotates, the old activity is destroyed but cannot be collected, along with its whole view tree. Long-lived objects should hold the application context or nothing.

Application

The Application object is created first in every process, before any activity, service or receiver. Subclass it to run process-wide setup in onCreate(): dependency injection, logging, crash reporting. Two details matter. First, Application.onCreate() runs on the main thread before the first screen can draw, so everything in it is start-up time. Second, it runs in every process of your app, including a background process started only for a broadcast or a service.

ContentProviders are created even earlier: after the Application is attached, but before its onCreate(). Libraries used to abuse this by shipping empty providers just to initialise themselves, which is why the App Startup library (chapter 21) exists.

RememberMatch the context to the lifetime of the object holding it. When in doubt in long-lived code, use applicationContext.

05Lifecycle · Callbacks, recreation, process death

Built to be destroyed.

An activity does not decide when it starts or stops. The system calls it, through a fixed set of lifecycle callbacks, on the main thread, as the user moves around and as resources change.

onCreate
The instance exists. Set the content view, restore state, wire observers. Runs once per instance.
onStart
The activity is becoming visible.
onResume
It is in the foreground and receiving input.
onPause
It is losing focus: a dialog-style activity covers it, or the user is leaving. Keep this quick; the next activity cannot resume until it returns.
onStop
It is no longer visible. Release anything the user cannot see, such as camera previews and location updates.
onDestroy
The instance is being destroyed, because it finished or because of a configuration change. It is not guaranteed to run if the process is killed.

The Jetpack Lifecycle library turns these callbacks into observable state: INITIALIZED, CREATED, STARTED, RESUMED and DESTROYED. Activities and fragments are LifecycleOwners, so any other class can observe them instead of the activity calling it from every callback. Coroutine scopes and Flow collection hang off the same lifecycle, as chapters 12 and 13 show.

Configuration changes

A configuration change is any change to the device configuration the app is running in: rotation, dark mode, language, font size, keyboard, or the window being resized in split screen or on a foldable. By default Android handles it in the bluntest way possible. It destroys the activity and creates a new instance, so that every resource is loaded again for the new configuration.

Every field in the old instance is lost. Two mechanisms survive the change:

  • The ViewModel. Each activity has a ViewModelStore that the system hands from the old instance to the new one during a configuration change. ViewModels in it survive, and only get onCleared() when the activity finishes for good.
  • Saved instance state. Before the activity stops, the system calls onSaveInstanceState() with a Bundle. The new instance receives that Bundle in onCreate().

You can declare android:configChanges to handle some changes yourself without recreation. Compose apps often do this for orientation and screen size, since Compose recomposes when the configuration changes. It is a choice to make deliberately, for specific changes, never as a way to avoid handling state.

Process death

Now the harder case. The user leaves your app, opens the camera and three other apps, and the system kills your cached process to free memory. Later they return to your app from Recents. Android starts a new process, recreates the activity they were on, and passes it the saved instance state it kept from before. The user sees the same screen. Your ViewModels, singletons and in-memory caches are all gone.

Process death is the bug most Android apps ship. Nothing crashes during development, because a phone on a desk rarely runs low on memory. Test it on purpose: put the app in the background and run adb shell am kill your.package.name, or enable “Don't keep activities” in developer options for a rougher approximation.

Try it: three counters, three lifetimes

The simulated screen below keeps one counter in three places: a plain field in the Activity, a StateFlow in the ViewModel, and a SavedStateHandle. Add to them, then rotate, leave, kill the process and return, and watch which survives what.

Process
not running
Activity
none
ViewModel
none
Activity field
none
ViewModel StateFlow
none
SavedStateHandle
none

    What saved state can hold

    The saved Bundle is stored by system_server, outside your process, which is how it survives process death. That means it crosses Binder, which means it must be small: IDs, scroll positions, the text in a half-filled form, which tab is selected. Never a list of loaded items or a bitmap. Since Android 9, onSaveInstanceState() runs after onStop().

    Modern code rarely overrides it directly. A ViewModel takes a SavedStateHandle, a key-value map that is written into the same Bundle, and Compose has rememberSaveable, which writes into it too.

    RememberThree lifetimes: a field lives as long as one activity instance; a ViewModel survives configuration changes; saved state survives process death. Put each piece of state in the shortest lifetime that still keeps the user's work.

    06Components · Tasks, back, windows

    Stacks of screens.

    A task is a stack of activities, the back stack, that the user experiences as one app in Recents. Starting an activity normally pushes it onto the current task. Back pops it, destroying it. Since Android 12, pressing Back on the root activity of a launcher task no longer finishes it; the task moves to the background instead, so returning is a warm start.

    Launch modes and flags

    Launch modes, declared in the manifest, and intent flags, set by the caller, change where a new activity goes.

    standard
    The default. Every start creates a new instance on top of the current task.
    singleTop
    If an instance is already on top, reuse it and deliver the intent to onNewIntent().
    singleTask
    At most one instance, as the root of its task. Starting it again clears everything above it.
    singleInstance
    Like singleTask, but alone in its task forever.
    singleInstancePerTask
    Since Android 12: the root of its task, with one instance per task, allowing several tasks.

    Flags such as FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP do the same from the caller's side, and taskAffinity decides which task an activity prefers. These rules interact in surprising ways, which is one reason most modern apps use a single activity and handle navigation inside it (chapter 14).

    Back is a callback

    Overriding onBackPressed() is deprecated. Back now goes through the OnBackPressedDispatcher: components register an OnBackPressedCallback, enable it only while they want to intercept Back, and the dispatcher calls the most recent enabled one. The system needs to know in advance whether your app will handle Back, because of predictive back: as the user starts the gesture, the system shows a preview of where Back will go, such as the home screen or the previous activity, and can only do so if no callback is going to intercept it.

    Windows and insets

    Every activity owns a window, managed by WindowManagerService. The status bar, navigation bar, display cut-outs and the on-screen keyboard all overlap that window, and the sizes of those overlaps are window insets. Since Android 15, apps that target it are drawn edge-to-edge by default, behind the system bars, and must apply insets as padding themselves so content stays tappable. Since Android 16, apps targeting it can no longer opt out. The same release, on large screens, ignores orientation and resizability locks for apps that target it, so every screen must work at any size.

    RememberDesign every screen to be resized and drawn edge-to-edge. The system increasingly decides the window's size and shape, not your manifest.

    07Fragments · Two lifecycles, one transaction

    Screens inside screens.

    A Fragment is a reusable portion of UI with its own lifecycle, hosted by an activity or by another fragment. Fragments arrived with tablets, so one activity could show a list and a detail side by side, and they became the standard way to build single-activity apps with the View system.

    The FragmentManager

    Every activity has a FragmentManager that adds, removes and replaces fragments, and each fragment has a childFragmentManager for the fragments inside it. Changes happen in a transaction:

    supportFragmentManager.commit {
        setReorderingAllowed(true)
        replace<DetailFragment>(R.id.container, args = bundleOf("id" to id))
        addToBackStack("detail")
    }

    commit() is asynchronous: the change is scheduled on the main thread, not applied immediately. addToBackStack() records the transaction so Back reverses it. A commit after the activity has saved its state throws an IllegalStateException, because the change could not be restored after process death.

    The FragmentManager recreates fragments itself after a configuration change or process death, using reflection on their no-argument constructor. This is why fragments must have one, and why arguments go in arguments, a Bundle that is saved and restored, never in a constructor.

    Two lifecycles

    A fragment's lifecycle runs onAttach, onCreate, onCreateView, onViewCreated, onStart, onResume, then in reverse onPause, onStop, onDestroyView, onDestroy and onDetach. The detail that causes most fragment bugs is that the fragment and its view have separate lifecycles. When a fragment is replaced and put on the back stack, its view is destroyed (onDestroyView) but the fragment object stays alive. When the user comes back, a new view is created for the same fragment.

    Observe UI data with viewLifecycleOwner, not the fragment itself. Observers tied to the fragment keep running while its view is gone, and a new one is added each time the view is recreated, so updates arrive twice, then three times.

    The same applies to view binding: a fragment that keeps its binding in a field must clear it in onDestroyView(), or it holds a whole destroyed view tree in memory.

    Talking between fragments

    Fragments should not hold references to each other. Two approaches replace that. A ViewModel scoped to the activity, or to a navigation graph, can be shared by several fragments. For one-off results, the Fragment Result API lets one fragment call setFragmentResult(key, bundle) and another register a listener for that key; the FragmentManager delivers it once the listener is at least STARTED.

    Dialogs follow the same rule. A DialogFragment is recreated with its host and survives rotation; a bare Dialog is destroyed with the activity and leaks its window.

    RememberA fragment can outlive its view. Anything that touches views belongs to viewLifecycleOwner, and must be released in onDestroyView().

    08Threads · Looper, Handler, Choreographer, ANR

    One thread to run them all.

    Each app process has one main thread, also called the UI thread. It runs every lifecycle callback, every click handler, every layout pass and every draw, and the UI toolkit is not thread-safe: only the main thread may touch views. Understanding how that thread schedules work explains most Android performance problems.

    Looper, MessageQueue, Handler

    The main thread runs a Looper, a loop that takes the next Message from its MessageQueue, dispatches it, and repeats. The queue is ordered by time; when nothing is due, the thread sleeps in the kernel (through epoll) until a message arrives or a timer expires. A Handler is how anything puts work on a particular Looper's queue: handler.post(runnable) now, postDelayed() later.

    Everything arrives this way. Lifecycle events come from system_server over Binder and are posted to the main queue. Input events arrive through a socket the Looper also watches. Your View.post(), runOnUiThread() and Dispatchers.Main all end in a Handler posting to this queue.

    Choreographer and vsync

    The display refreshes on a fixed beat, vsync: every 16.7 ms at 60 Hz, 8.3 ms at 120 Hz. The Choreographer listens for that signal and, on each one, runs that frame's work in a fixed order: input events first, then animations, then traversal, which is measure, layout and draw for any view tree that needs it. Calling invalidate() or requestLayout() on a view does not draw anything immediately; it asks the window's ViewRootImpl to schedule a traversal for the next vsync.

    Drawing on the main thread does not produce pixels. It records drawing commands into display lists. The RenderThread, a separate thread in your process, turns those lists into GPU commands and fills a buffer. The buffer goes to SurfaceFlinger, the system compositor, which combines it with the status bar, navigation bar and other windows, and hands the result to the display.

    Jank and ANRs

    If the main thread's work for a frame overruns the vsync interval, the frame misses its deadline and the previous one stays on screen: jank. If the main thread does not respond to an input event within 5 seconds, the system declares an ANR, Application Not Responding, and offers to close the app. Broadcast receivers and services have their own, longer, deadlines. Google Play counts your ANR rate as a core quality metric and can reduce your app's visibility if it is too high.

    The usual causes are disk and network access, large JSON parsing, database queries, lock contention with a background thread, and synchronous Binder calls to a slow system service. StrictMode, enabled in debug builds, flags disk and network access on the main thread as it happens.

    RememberThe main thread is a queue, and every message in it delays every frame behind it. Keep main-thread work short, and move anything that waits on I/O to a background dispatcher.

    09UI · Views, measure, layout, draw

    The original toolkit.

    Until Compose, every Android screen was a tree of View objects. A View is a rectangle that measures, positions and draws itself and handles touches. A ViewGroup is a View that contains other Views and decides where they go: LinearLayout, FrameLayout, ConstraintLayout. Screens are usually described in XML layouts that the LayoutInflater turns into objects at run time, by parsing the precompiled XML and constructing each View by reflection.

    Three passes

    1. Measure. Each parent asks each child how big it wants to be, passing a MeasureSpec: EXACTLY this size, AT_MOST this size, or UNSPECIFIED. Children answer with setMeasuredDimension().
    2. Layout. Each parent places each child at a position within its own bounds.
    3. Draw. Each View draws its background, content and children into a Canvas, recorded as a display list on a RenderNode.

    Nested layouts that measure their children twice, such as weighted LinearLayouts and RelativeLayout, multiply the cost with every level. ConstraintLayout exists largely to flatten those trees into one level. Two calls start the passes: requestLayout() when size or position may change, invalidate() when only appearance does. Changing properties such as translationX, alpha or rotation needs neither; they update the RenderNode directly, which is why animations should use them.

    RecyclerView

    A list of ten thousand items cannot have ten thousand Views. RecyclerView creates only enough item views to fill the screen, plus a few, and reuses them as they scroll off. Its parts:

    Adapter
    Creates ViewHolders and binds data to them by position.
    ViewHolder
    Holds one item view and its child references, so binding needs no lookups.
    LayoutManager
    Positions items: linear, grid or staggered.
    RecycledViewPool
    Keeps detached ViewHolders by type for reuse.
    DiffUtil
    Computes the smallest set of inserts, removals and moves between two lists. ListAdapter runs it on a background thread.

    View binding generates a class per XML layout with typed, null-safe references to its views, which replaced findViewById() and the deprecated Kotlin synthetics.

    Views are not legacy in the sense of disappearing. The framework itself is Views, Compose runs inside one, and maps, video players, web views and many SDKs still are Views. You will read and interoperate with them for years.

    RememberMeasure, layout and draw run on the main thread for every frame that needs them. Flat trees, recycled lists and property-based animations keep each pass cheap.

    10UI · Composition, state, recomposition

    UI as a function of state.

    Jetpack Compose replaces mutating a tree of Views with describing the UI for the current state. A @Composable function takes state and emits UI. When the state changes, Compose calls the affected functions again and updates the screen to match. You never write textView.text = ...; you change the state the text was read from.

    @Composable
    fun Counter(count: Int, onAdd: () -> Unit) {
        Button(onClick = onAdd) {
            Text("Added $count")
        }
    }

    What the compiler does

    Compose is a Kotlin compiler plugin plus a runtime. The plugin rewrites every composable function to take extra parameters, a Composer and change flags, and wraps its body in groups recorded in the slot table, a gap-buffer structure holding the composition: which functions ran, in what positions, with what remembered values. Because identity comes from position in the code, Compose can tell that the second Text in a Column is the same element as last time. In loops, where position is ambiguous, key() supplies the identity.

    The whole Compose tree sits inside a single Android View, AndroidComposeView, which is how it lives in an activity, in a fragment or inside a View layout.

    State and the snapshot system

    State that Compose can observe is created with mutableStateOf() or its relatives. Reads and writes go through the snapshot system, a transactional in-memory store. While a composable runs, Compose records every state object it reads. When a write to one of those objects is applied, the composables that read it are invalidated and scheduled for recomposition on the next frame.

    A composable function can run at any time, in any order, many times per second, and may be skipped entirely. So it must be free of side effects, and any value that should outlive a single call needs remember { }, which stores it in the slot table. rememberSaveable also writes it to saved instance state, so it survives recreation and process death.

    Skipping and stability

    Recomposition is cheap because most of it is skipped. When a parent recomposes, a child whose parameters are all equal to last time is not called. This needs Compose to trust each parameter's equals(), a property called stability. Primitives, strings, immutable data classes and function types are stable. Types from modules Compose did not compile, and standard Lists, are not proven stable. Since Kotlin 2.0.20, strong skipping is on by default: composables with unstable parameters can still be skipped when those parameters are the same instance, and lambdas are remembered automatically.

    Three phases

    Each frame Compose runs three phases, and a state read only invalidates the phase it happened in and those after it:

    1. Composition. Run composables, build or update the tree of layout nodes.
    2. Layout. Measure and place each node. Like Views, but each child is measured once, which keeps deep trees linear.
    3. Drawing. Draw each node into a canvas.

    That is a performance tool. A scroll-linked offset read in Modifier.offset { }'s lambda runs only in layout, so scrolling never recomposes. Read the same value in the composable's body and every scroll frame recomposes it.

    Side effects

    Work that must leave the composition goes through effect APIs that tie it to the composition's lifecycle.

    LaunchedEffect(key)
    Launches a coroutine when it enters the composition, cancels and restarts it when the key changes, and cancels it when it leaves.
    DisposableEffect(key)
    Sets something up and requires an onDispose to tear it down: register and unregister a listener.
    SideEffect
    Runs after every successful recomposition, to publish Compose state to non-Compose code.
    rememberCoroutineScope
    A scope for launching coroutines from event handlers such as clicks.
    derivedStateOf
    A state computed from other states that only notifies readers when its result changes.
    produceState
    Turns a non-Compose source into state, from a coroutine.

    Modifiers, lists and locals

    A Modifier is an ordered chain describing an element's size, padding, background, clipping and input handling. Order matters: padding then background draws the background inside the padding; the reverse draws it under it. LazyColumn and LazyRow compose only visible items, the Compose equivalent of RecyclerView; give items a stable key so state and animations follow the item, not the position. CompositionLocal passes values implicitly down the tree, which is how MaterialTheme and LocalContext reach every composable without parameters.

    RememberComposables describe; state drives. Keep state in as few places as possible, read it as late as possible, and let Compose skip the rest.

    11UI · Resources, density, themes, accessibility

    One app, ten thousand devices.

    Android runs on screens from watches to televisions, in hundreds of languages. Resources are how one APK adapts. Strings, dimensions, colours, layouts and drawables live in res/, and directory qualifiers provide alternatives: values-fr/ for French, values-night/ for dark mode, layout-sw600dp/ for screens at least 600 dp wide, drawable-xxhdpi/ for dense screens. At run time the system picks the best match for the current configuration, which is why a configuration change recreates the activity: the right resources may now be different ones.

    dp and sp

    Screens vary in pixel density, so sizes are given in density-independent pixels (dp), where one dp is one pixel at 160 dpi and scales with density. Text uses sp, which also scales with the user's font size setting. Since Android 14, that scaling is non-linear up to 200%, so large text grows less than small text. Layouts must survive it.

    Themes and styles

    A style is a set of attributes for one view. A theme is a set of attributes applied to a whole Context, and views resolve attributes such as ?attr/colorPrimary against it. This is why the Activity context matters for inflating views: it carries the theme. Material 3 is Google's current design system, available for both Views and Compose, and on Android 12 and later it can take dynamic colour from the user's wallpaper.

    Accessibility

    Accessibility services such as TalkBack read a tree describing the UI: in Views, the accessibility node tree; in Compose, the semantics tree. Every interactive element needs a label (contentDescription or text), touch targets need to be at least 48 by 48 dp, and custom controls must report their role and state. The semantics tree is also what Compose UI tests query, so accessible code is testable code.

    RememberNever hard-code a string, size or colour in a layout or composable. Resources and themes are the system's way of adapting your UI to a device you never tested on.

    12Concurrency · Suspend, scopes, dispatchers

    Waiting without blocking.

    Before coroutines, Android had AsyncTask (deprecated), raw threads, executors, callbacks and RxJava. Kotlin coroutines replaced them with sequential-looking code that pauses instead of blocking. A coroutine waiting for a network response holds no thread; the thread goes back to running other work until the response arrives.

    What suspend compiles to

    A suspend function is an ordinary function with a hidden extra parameter, a Continuation: an object recording where the function should resume and holding its local variables. The compiler turns the function body into a state machine with one state per suspension point.

    suspend fun loadProfile(id: String): Profile {
        val user = api.user(id)        // suspension point 1
        val posts = api.posts(user.id) // suspension point 2
        return Profile(user, posts)
    }
    
    // roughly what the compiler emits
    fun loadProfile(id: String, cont: Continuation<Profile>): Any? {
        val sm = cont as? LoadProfileSM ?: LoadProfileSM(cont)
        when (sm.label) {
            0 -> { sm.label = 1; val r = api.user(id, sm); if (r == COROUTINE_SUSPENDED) return r; sm.user = r as User }
            1 -> { sm.label = 2; ... }
            2 -> return Profile(sm.user, sm.result as List<Post>)
        }
    }

    When a call returns the special value COROUTINE_SUSPENDED, the function returns immediately and frees the thread. When the result is ready, someone calls continuation.resumeWith(result), which re-enters the function at the saved label. A suspended coroutine costs a few small objects on the heap, which is why you can run a hundred thousand of them.

    Scopes, jobs and structured concurrency

    Coroutines start from a CoroutineScope with a builder: launch for fire-and-forget work returning a Job, async for work returning a Deferred result you await(). Each coroutine's Job becomes a child of the scope's Job, forming a tree. This is structured concurrency, and it gives three guarantees:

    • A parent does not complete until all its children have.
    • Cancelling a parent cancels all its children.
    • A child's failure cancels its parent, and so its siblings, so no error is silently lost.

    A SupervisorJob changes the third rule: a failing child does not cancel its siblings or parent. That is what UI scopes want, since one failed request should not cancel the rest of the screen's work. Android provides the scopes you need. viewModelScope uses a SupervisorJob and Dispatchers.Main.immediate, and is cancelled in onCleared(). lifecycleScope is cancelled when its activity or fragment is destroyed. GlobalScope belongs to nothing and is almost always a leak.

    Dispatchers

    Main
    The main thread, through a Handler on the main Looper. Main.immediate runs straight away if already on the main thread, instead of posting.
    Default
    CPU-bound work: sorting, parsing, diffing. One thread per CPU core, at least two.
    IO
    Blocking calls: files, legacy blocking APIs. Up to 64 threads by default, shared with Default's pool.

    withContext(Dispatchers.IO) { ... } switches dispatcher for one block and returns its result. A good convention is that suspend functions are main-safe: a repository function that reads a file switches to IO itself, so callers can call it from the main thread without thinking. Room and Retrofit's suspend functions already do this.

    Cancellation is cooperative

    Cancelling a coroutine does not stop its thread. It sets the Job to cancelling, and the coroutine stops at its next suspension point, which throws a CancellationException. A tight loop with no suspension points will run to the end; check ensureActive() or call yield() inside it. Cleanup that must itself suspend goes in withContext(NonCancellable).

    // Swallows cancellation: the coroutine keeps running after its screen is gone.
    val result = runCatching { repository.refresh() }
    
    // Lets cancellation through.
    try {
        repository.refresh()
    } catch (e: IOException) {
        _state.update { it.copy(error = e.message) }
    }

    Where exceptions go

    An exception in launch propagates up the Job tree immediately. An exception in async is stored and thrown from await(), but in a regular scope it still cancels the parent. A CoroutineExceptionHandler only works on a root coroutine, and is a last-resort logger, not a way to recover. Recover where you can act: try/catch around the call, and coroutineScope { } or supervisorScope { } to group parallel work with the failure rules you want.

    RememberEvery coroutine belongs to a scope, and every scope belongs to a lifecycle. Never catch CancellationException without rethrowing it.

    13Concurrency · Cold, hot, lifecycle-aware

    Values over time.

    A suspend function returns one value. A Flow emits many, over time: database rows as they change, search results as the user types, location updates. A Flow is cold: it is a recipe, and nothing runs until a terminal operator such as collect() is called. Each collector runs the recipe again, from the start.

    Between producer and collector sit operators: map, filter, combine for several sources, flatMapLatest to switch to a new inner flow and cancel the previous one, debounce for typing, distinctUntilChanged. flowOn(Dispatchers.IO) changes the dispatcher of everything upstream of it; a flow never changes the context its collector runs in. catch handles errors from upstream only.

    When the producer is faster than the collector, buffer() lets them run concurrently, conflate() drops intermediate values, and collectLatest cancels the collector's previous work when a new value arrives.

    StateFlow and SharedFlow

    Hot flows exist independently of collectors. A StateFlow always holds exactly one current value, gives it to each new collector immediately, and only emits when the new value is not equal to the previous one. It is the standard container for UI state. A SharedFlow broadcasts to every collector, with a configurable replay cache and buffer. A Channel is a hot queue in which each element goes to exactly one receiver. callbackFlow wraps a callback API in a Flow, with awaitClose { } to unregister.

    Turning cold into hot

    A ViewModel usually exposes a cold source, such as a Room query, as a StateFlow with stateIn:

    val uiState: StateFlow<CartUiState> = cartRepository.items
        .map { items -> CartUiState(items = items, total = items.sumOf { it.price }) }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = CartUiState.Loading,
        )

    WhileSubscribed(5_000) keeps the upstream running for five seconds after the last collector leaves. A rotation recreates the UI well within that, so the database query is not restarted; leaving the app for longer stops it, so nothing runs in the background for a screen no one can see.

    Collecting safely

    A coroutine launched in lifecycleScope keeps collecting while the app is in the background, wasting work and sometimes touching views that should not be touched. Collect inside repeatOnLifecycle, which starts collection when the lifecycle reaches STARTED and cancels it at STOPPED:

    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiState.collect { render(it) }
        }
    }

    In Compose, collectAsStateWithLifecycle() does the same and turns the flow into Compose state.

    One-off events

    Navigation after a save, or a snackbar message, are hard to model as flows. A SharedFlow without replay drops an event if no one is collecting at that moment, for example during a rotation; a Channel delivers it once but can still lose it in a narrow window. Google's architecture guidance is to model them as state: put the message in the UI state, and have the UI tell the ViewModel when it has been shown, so the ViewModel clears it.

    RememberExpose state as StateFlow, build it with stateIn(WhileSubscribed), and collect it only while the UI is started.

    14Architecture · Layers, state, navigation

    Where each piece of code lives.

    Android's lifecycle rules make one architectural decision for you: the activity is a bad place for anything that matters, because it is destroyed constantly. Google's recommended architecture follows from that, in three layers.

    UI layer
    Composables or Views that render state, plus the ViewModels that produce it.
    Domain layer
    Optional. Use cases: small classes holding business logic reused by several ViewModels.
    Data layer
    Repositories that own the app's data and decide where it comes from.

    Dependencies point one way. The UI knows about the data layer; the data layer knows nothing about screens.

    ViewModel and UI state

    A ViewModel holds a screen's state and logic, survives configuration changes in the ViewModelStore, and offers viewModelScope for its work. It should not hold a Context, a View or anything else with a shorter lifetime. It exposes one immutable UI state object, usually a data class or a sealed interface such as Loading, Content and Error, through a StateFlow. Values that must survive process death, such as the ID of the item on screen and the search query, go through a SavedStateHandle.

    Unidirectional data flow

    State flows down: the ViewModel exposes state and the UI renders it. Events flow up: the UI calls ViewModel functions such as onAddToCart(id). The UI never changes state directly. This pattern, unidirectional data flow, is what MVVM and MVI both implement on Android, and it makes every screen a pure function of one state object, which is easy to test and to restore.

    Repositories and a single source of truth

    A repository is the only door to a type of data. Inside, it may combine a Room database, a network API and an in-memory cache, but callers see only functions and flows. The strongest version is offline-first: the local database is the single source of truth. The UI observes the database; network refreshes write into the database; the change reaches the UI through the database's flow. The app works offline, and there is exactly one place where any piece of data can be wrong.

    Navigation

    Modern apps usually have a single activity and move between destinations inside it. The Navigation component maps routes to destinations, which can be composables or fragments, and manages the back stack, arguments, deep links and the system Back button. Recent versions define routes as @Serializable Kotlin types, so arguments are type-checked. Navigation 3, a newer Compose-first library, takes a different approach: the back stack is a list of keys that you own and change directly.

    RememberThe UI renders one state object and sends events up. The ViewModel turns events into state. The repository owns the data, and the database is its source of truth.

    15Architecture · Hilt and Dagger

    Who creates what.

    A ViewModel needs a repository, which needs a DAO and an API client, which need a database and an HTTP client, which need a Context. Dependency injection means each class receives its dependencies through its constructor instead of creating them, so one place builds the graph and tests can pass fakes.

    The system creates activities, fragments and ViewModels itself, so you cannot pass them constructor arguments directly. Hilt, Jetpack's injection library built on Dagger, solves this. Dagger generates the code that builds the graph at compile time, so a missing binding is a build error, not a crash. Hilt adds a fixed set of components bound to Android lifecycles.

    SingletonComponent
    The whole process. @Singleton.
    ActivityRetainedComponent
    Survives configuration changes. @ActivityRetainedScoped.
    ViewModelComponent
    One ViewModel. @ViewModelScoped.
    ActivityComponent
    One activity instance. @ActivityScoped.
    FragmentComponent
    One fragment. @FragmentScoped.
    ServiceComponent
    One service. @ServiceScoped.
    @HiltViewModel
    class CartViewModel @Inject constructor(
        private val cartRepository: CartRepository,
        savedStateHandle: SavedStateHandle,
    ) : ViewModel()
    
    @Module
    @InstallIn(SingletonComponent::class)
    abstract class DataModule {
        @Binds abstract fun cartRepository(impl: OfflineFirstCartRepository): CartRepository
    }

    @HiltAndroidApp on the Application starts the graph; @AndroidEntryPoint lets an activity or fragment receive injections. A class with an @Inject constructor needs nothing else. For interfaces and third-party types, a module installed in a component provides them: @Binds maps an interface to an implementation, @Provides builds an object in code. An unscoped binding gives a new instance every time; a scope annotation gives one instance per component.

    Koin is a popular alternative that resolves dependencies at run time instead, with less setup and less checking. Small apps often need no library at all: one hand-written container class in the Application does the same job.

    RememberScope an object to the lifetime it needs, and no longer. A @Singleton that holds an activity is a leak with an annotation on it.

    16Data · Room, DataStore, files

    What survives the process.

    Every app has private internal storage, filesDir and cacheDir, readable only by its own Linux user. The system may delete the cache directory when space runs low. Everything that must outlive the process lives here, in one of three forms.

    Room

    Room is a layer over SQLite. You declare @Entity classes for tables, a @Dao interface of annotated queries, and a @Database class; KSP generates the implementation, and every SQL query is checked against the schema at compile time.

    @Dao
    interface CartDao {
        @Query("SELECT * FROM cart_item ORDER BY added_at")
        fun observeItems(): Flow<List<CartItemEntity>>
    
        @Upsert
        suspend fun upsert(item: CartItemEntity)
    }

    Suspend functions run off the main thread. Functions returning Flow are re-run whenever a table they read changes: Room's invalidation tracker installs SQLite triggers on those tables and re-queries when one fires. This is what makes the database work as a single source of truth. When the schema changes, you bump the version and provide a migration, written by hand or generated with @AutoMigration from exported schema files. A missing migration crashes at launch, or, with destructive fallback enabled, silently deletes the user's data.

    DataStore and SharedPreferences

    SharedPreferences is the original key-value store: an XML file loaded fully into memory. Its first read blocks the calling thread until the file loads, and pending apply() writes are flushed synchronously when an activity stops, a known cause of ANRs. DataStore replaces it. Preferences DataStore stores keys and values; Proto DataStore stores a typed object. Both read through Flow, write through suspend functions in transactions, and never block the main thread. Neither suits large or relational data; that is Room's job.

    Files and shared storage

    Since Android 10, scoped storage limits what apps can see of shared storage. An app can always write its own files and add media through MediaStore, the system's index of photos, videos, audio and downloads. Reading other apps' media needs a permission, and opening an arbitrary document goes through the Storage Access Framework's system picker, which grants access to the one file the user chose.

    RememberStructured data goes in Room, small settings in DataStore, large blobs in files. Write a migration for every schema change, and test it.

    17Data · OkHttp, Retrofit, TLS

    Talking to servers.

    Network access needs only the INTERNET permission, granted at install. It is forbidden on the main thread: since Android 3.0, trying throws NetworkOnMainThreadException. Since Android 9, plain HTTP is blocked by default for apps targeting it.

    Almost every app's networking runs on OkHttp, an HTTP client with a connection pool, HTTP/2 multiplexing, transparent compression, response caching and automatic retries on connection failures. Its central idea is the interceptor chain. Application interceptors see each logical call once, which suits adding auth headers and logging. Network interceptors see every actual request, including redirects and retries.

    Retrofit sits on top. You write an interface:

    interface ShopApi {
        @GET("products/{id}")
        suspend fun product(@Path("id") id: String): ProductDto
    }

    Retrofit creates an implementation at run time with a dynamic proxy. Each call builds an OkHttp request from the annotations, executes it, and converts the JSON body to your type with a converter: kotlinx.serialization, Moshi or Gson. Suspend functions are main-safe. Ktor's client is the main alternative, common in Kotlin Multiplatform code.

    Map network models (DTOs) to your own domain models at the repository boundary, so a change in the API's JSON does not reach the UI. Treat every failure as normal: timeouts, airplane mode, captive portals, expired tokens. ConnectivityManager's network callbacks report connectivity, but the only real test of a connection is a request.

    The network security config, an XML file referenced from the manifest, declares which certificate authorities the app trusts, per domain, whether cleartext is allowed, and optional certificate pins, all without code.

    RememberAll network I/O off the main thread, all failures expected, all API types mapped at the edge of the data layer.

    18Background · Services, WorkManager, Doze

    Work after the screen goes away.

    Background work is where Android has changed the most, always in the same direction: less freedom for apps, more battery for users. Most of the rules are restrictions on what used to be allowed.

    The restrictions

    • Doze (Android 6): when the device is unplugged and still, the system defers jobs, alarms and network access to occasional maintenance windows.
    • Background execution limits (Android 8): background apps cannot start services freely, and implicit broadcasts no longer wake manifest receivers.
    • App Standby Buckets (Android 9): apps are ranked active, working set, frequent, rare or restricted by how recently they were used, and each bucket gets less background time.
    • Foreground service limits (Android 12): apps in the background generally cannot start foreground services.
    • Foreground service types (Android 14): every foreground service declares a type, such as location, mediaPlayback or dataSync, with a matching permission, and some types have run-time limits.

    Services

    A Service runs on the main thread like any other component; it is a lifetime, not a thread. A foreground service shows an ongoing notification and is treated as important as a visible app, which is right for work the user knows about and expects to continue: a music player, navigation, a call, an active workout. A bound service lets clients connect and call methods on it, across processes through Binder and an AIDL interface.

    WorkManager

    For deferrable work that must eventually run, such as uploading a photo, syncing data or sending logs, use WorkManager. You describe the work and its constraints, and WorkManager guarantees it runs even if the app is killed or the device restarts, because the request is persisted in its own database.

    val sync = PeriodicWorkRequestBuilder<SyncWorker>(6, TimeUnit.HOURS)
        .setConstraints(Constraints(requiredNetworkType = NetworkType.UNMETERED))
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
        .build()
    
    WorkManager.getInstance(context)
        .enqueueUniquePeriodicWork("sync", ExistingPeriodicWorkPolicy.KEEP, sync)

    Underneath, it schedules through the system's JobScheduler, which batches work from all apps to wake the radio and CPU less often. Workers can be chained, given unique names so they are not duplicated, observed as Flows, retried with backoff, and marked expedited for short work that should start immediately. Periodic work runs at most every 15 minutes. A CoroutineWorker runs its doWork() as a suspend function and is cancelled when its constraints stop being met.

    Alarms

    AlarmManager fires a PendingIntent at a time. Inexact alarms are batched. Exact alarms need the SCHEDULE_EXACT_ALARM permission since Android 12, which since Android 14 is no longer granted by default to most newly installed apps; alarm clocks and calendars can use USE_EXACT_ALARM instead. Most apps that think they need an exact alarm need WorkManager or a push message.

    RememberIf the user can see it happening, use a foreground service. If it can wait, use WorkManager. If it must happen at an exact time, check whether it really must.

    19Security · Permissions, notifications, Keystore

    Asking, and keeping secrets.

    Permissions are the controlled exceptions to the app sandbox. Every one is declared in the manifest. Normal permissions, such as internet access, are granted at install. Signature permissions are granted only to apps signed with the same key as the declaring app. Dangerous permissions, covering location, camera, microphone, contacts and media, must also be granted by the user at run time, and can be revoked at any time from Settings. Android 11 added one-time grants, and revokes permissions from apps unused for months.

    Asking at run time

    Permission requests, like starting another activity for a result, go through the Activity Result API. You register a launcher with a contract, which must happen before the activity or fragment is STARTED (in practice, as a property initialiser), because after process death the result is delivered to the new instance through that registration.

    private val requestCamera =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            if (granted) openCamera() else showCameraExplanation()
        }

    Ask in context, when the user starts the feature that needs it. If they have refused once, shouldShowRequestPermissionRationale() returns true and you should explain before asking again. After a second refusal, the system stops showing the dialog, and only Settings can grant it.

    Often the best permission is none. The photo picker returns the images the user chose with no storage permission. Since Android 14, users can also grant access to selected photos only, and apps must handle that partial grant. The Storage Access Framework does the same for documents.

    Notifications

    Since Android 8, every notification belongs to a channel, which the user controls: importance, sound, whether it shows at all. Since Android 13, posting notifications needs the run-time POST_NOTIFICATIONS permission. Tapping a notification fires its PendingIntent.

    Secrets

    The Android Keystore generates and stores cryptographic keys inside secure hardware where the device has it (a trusted execution environment, or a separate StrongBox chip). Your app can use a key to encrypt, decrypt or sign, but cannot read the key itself, even with root on a compromised device. A key can require the user to authenticate with BiometricPrompt before each use. Jetpack Security's EncryptedSharedPreferences has been deprecated; the current pattern is to encrypt data yourself with a Keystore key before writing it to DataStore or a file.

    Anything shipped in the APK, including API keys in BuildConfig, can be extracted. Secrets that matter belong on a server. The Play Integrity API lets that server check that a request comes from your unmodified app, installed from Play, on a genuine device.

    RememberAsk for the fewest permissions, at the moment they are needed. Store keys in the Keystore and real secrets on a server.

    20Native · NDK, JNI, ABIs

    Below the runtime.

    Most of Android's own machinery is C and C++: ART, Skia, the media framework, SQLite. Apps can add their own native code with the Native Development Kit (NDK). It is the right tool for reusing an existing C or C++ library, for game engines, and for signal processing, audio, image work and machine learning where tight control of memory matters. It is rarely faster for ordinary app logic, because crossing into native code has a cost of its own.

    JNI

    Kotlin and C++ meet through the Java Native Interface. Kotlin declares a function with external, loads the library with System.loadLibrary("name"), and the runtime binds the call to a C function with a mangled name, or one registered in JNI_OnLoad. Native code receives a JNIEnv* through which it reads Kotlin objects, calls methods and throws exceptions.

    • A JNIEnv is valid only on the thread that received it. Native threads must attach to the runtime first.
    • Local references are freed when the native call returns; keeping an object longer needs a global reference, which must be deleted by hand or it leaks.
    • A pending Java exception must be checked and cleared; calling most JNI functions with one pending is an error.
    • Every crossing has overhead. Make few calls that do a lot, not many that do a little.

    Building it

    Gradle drives CMake (or ndk-build) to compile a .so library for each ABI the app supports: arm64-v8a for nearly every current phone, armeabi-v7a for older 32-bit ones, x86_64 for emulators and some Chromebooks. The App Bundle delivers only the matching one to each device. Native crashes produce tombstones with raw addresses, so keep the unstripped libraries' debug symbols and upload them to Play Console or your crash reporter.

    Newer devices use 16 KB memory pages instead of 4 KB, and a native library aligned for 4 KB will not load on them. Since November 2025, Google Play requires new apps and updates targeting Android 15 or later to support 16 KB pages, which means rebuilding native code, including that inside third-party SDKs, with a recent NDK.

    RememberUse native code to reuse C++ or to do heavy computation, never to speed up ordinary app logic. Cross the JNI boundary rarely, and manage its references by hand.

    21Quality · Start-up, frames, memory

    Measured, never guessed.

    Android performance comes down to three numbers: how long the app takes to show something useful, how many frames miss their deadline, and how much memory it holds. All three must be measured on real, ideally low-end, devices, in release builds. Debug builds run interpreted, unoptimised code and are not representative.

    Start-up

    A cold start begins with no process: fork from Zygote, create the Application and its ContentProviders, create the first activity, inflate or compose its UI, run the first layout and draw the first frame. A warm start has a process but recreates the activity. A hot start only brings an existing activity forward. The platform reports time to initial display when the first frame draws, and time to full display when you call reportFullyDrawn() after the real content has loaded. The SplashScreen API, standard since Android 12, covers the gap.

    To make cold starts faster, do less in Application.onCreate() and the first screen, load lazily, and run library initialisers through App Startup, which replaces many ContentProviders with one. Then ship Baseline Profiles: a list of the classes and methods your start-up and key journeys use, generated by a Macrobenchmark test and packaged with the app. At install, ART compiles those methods ahead of time, so the first launch runs machine code instead of the interpreter. Google Play also gathers profiles from real users as Cloud Profiles.

    Frames

    Jank is any frame whose work misses the vsync deadline. To find it, record a system trace with Perfetto, the platform's tracing tool, from Android Studio or the device. It shows every thread on a timeline: each frame's work on the main thread and RenderThread, Binder calls, garbage collection, lock contention, CPU frequency. Add your own sections with trace("name") { }. Macrobenchmark measures start-up and frame timing in repeatable automated tests; JankStats reports janky frames from production.

    Memory

    Each app has a heap limit, typically a few hundred megabytes on a modern phone and much less on a low-end one. Exceed it and the app crashes with OutOfMemoryError; long before that, frequent garbage collection costs CPU and battery. The largest consumers are usually bitmaps, whose pixel data has lived in native memory since Android 8, so load images at the size they are displayed, through a library such as Coil or Glide.

    A leak is memory that is still reachable but will never be used again: a destroyed activity referenced by a singleton, a listener never unregistered, a fragment's binding kept after its view died. LeakCanary, added to debug builds, watches destroyed activities, fragments, views and ViewModels, takes a heap dump when one is not collected, and shows the chain of references keeping it alive. The memory profiler in Android Studio shows allocations as they happen.

    RememberProfile release builds on slow devices. Ship Baseline Profiles, trace jank with Perfetto, and keep LeakCanary in every debug build.

    22Quality · Local, instrumented, coroutines

    Tests on two machines.

    Android tests run in two places. Local tests, in src/test, run on your computer's JVM in seconds. They suit everything that does not need the framework: ViewModels, repositories, use cases, mappers. Instrumented tests, in src/androidTest, are packaged into an APK and run on a device or emulator, against the real framework. They are slower, and right for UI, database and integration tests. Gradle Managed Devices let Gradle create and run emulators for them automatically.

    Robolectric sits between: it runs framework code on the JVM against a simulated Android, so local tests can create activities and inflate layouts.

    UI tests

    Espresso drives View-based UIs: find a view, act on it, check it. It waits for the main thread to be idle before each step, which removes most timing flakiness; background work outside its knowledge needs an idling resource. Compose tests find nodes in the semantics tree, by text, content description or test tag, and synchronise with the composition automatically.

    @get:Rule val compose = createComposeRule()
    
    @Test fun showsTotalAfterAddingItem() {
        compose.setContent { CartScreen(state = CartUiState(items = listOf(shoes))) }
        compose.onNodeWithText("Total £79.00").assertIsDisplayed()
    }

    Coroutines and flows

    kotlinx-coroutines-test provides runTest, which runs a test on a TestDispatcher with virtual time: delay(10_000) completes instantly, and advanceUntilIdle() runs everything pending. Code that uses Dispatchers.Main needs Dispatchers.setMain(testDispatcher), and dispatchers should be injected rather than hard-coded, so tests can replace them. Turbine asserts on what a Flow emits, one item at a time.

    Prefer fakes (small working implementations, such as an in-memory repository) to mocks for your own types; they test behaviour rather than call sequences, and survive refactoring. Hilt can replace modules in tests with @TestInstallIn. Screenshot tests, through Compose Preview Screenshot Testing, Paparazzi or Roborazzi, catch visual regressions that assertions miss.

    RememberMost tests belong on the JVM. Inject dispatchers, test flows with virtual time, and keep device tests for what only a device can check.

    23Release · Play, rollouts, vitals

    Getting it onto phones.

    A release goes to Google Play as a signed App Bundle. Play generates device-specific APKs, signs them with the app signing key it holds, and delivers them through tracks: internal testing, closed testing, open testing and production. Production releases should use a staged rollout, starting at a few percent of users and increasing as the numbers hold. A rollout can be halted, but not undone: users who received the release keep it, so the fix is a new release with a higher versionCode.

    Android vitals in Play Console reports crash rate, ANR rate, excessive wake-ups and start-up time from real devices, with stack traces (deobfuscated with your uploaded R8 mapping file). Play treats user-perceived crash and ANR rates above set thresholds as bad behaviour and can show warnings on your store listing or reduce its visibility.

    Each year, Play raises the minimum targetSdk that new apps and updates must declare, to within about a year of the latest Android release. Every raise switches on that year's behaviour changes, so the yearly target bump is planned work, not a version number. In-app updates can prompt users to install a new version, flexibly in the background or immediately for critical fixes. Feature modules can be delivered on demand through Play Feature Delivery to keep the first download small.

    RememberUpload mapping files and native symbols with every release, roll out in stages, and watch vitals before going to 100%.

    24End to end

    One tap, every layer.

    Here is a single tap on an Add to cart button in a Compose app with an offline-first architecture, traced through every layer this essay has covered.

    1. Touch. The touchscreen driver reports the touch to the kernel. InputManagerService in system_server finds the window under the finger and sends the event through an input channel to your process.
    2. Main thread. The main Looper wakes, and on the next vsync Choreographer runs the input callback. ViewRootImpl hands the event to AndroidComposeView.
    3. Compose input. Compose hit-tests its layout nodes, finds the button's clickable modifier, and calls onClick, which calls viewModel.onAddToCart(id).
    4. Coroutine. The ViewModel launches in viewModelScope and calls the repository's suspend function.
    5. Dispatchers. Room switches to its query executor and inserts the row in a transaction. The main thread is free the whole time.
    6. Network. The repository enqueues a WorkManager request to sync the cart, constrained to a network connection. It will run even if the user leaves.
    7. Flow. Room's invalidation tracker sees the cart table change and re-runs the observed query. The new list flows through map, into the ViewModel's stateIn StateFlow.
    8. Compose state. collectAsStateWithLifecycle writes the new state into a snapshot state object. The cart badge composable read it, so it is invalidated.
    9. Frame. On the next vsync, Compose recomposes the badge, skips everything else, lays out and records drawing. The RenderThread issues GPU commands, SurfaceFlinger composites the window, and the badge shows 1.

    The tap took one frame to acknowledge and perhaps two to update, and no step held the main thread for more than a few milliseconds. When an app feels slow, it is because one of these steps does work that belongs to another.

    25The model

    Native Android in eight lines.

    1. Every app is a Linux process, forked from Zygote, that talks to system_server over Binder and can be killed whenever it is not in the foreground.
    2. Components declared in the manifest are the system's entry points, and the system, not your code, controls their lifecycles.
    3. Activities are destroyed constantly; ViewModels survive configuration changes; only saved state and storage survive process death.
    4. One main thread runs input, lifecycle, layout and drawing from a single queue, paced by vsync.
    5. Views and Compose both turn state into display lists; Compose makes the state explicit and skips what did not change.
    6. Coroutines wait without blocking, and every one belongs to a scope tied to a lifecycle. Flows deliver values over time, collected only while the UI is visible.
    7. The UI renders one state object, the ViewModel produces it, and repositories own the data, with the database as its source of truth.
    8. Background work, permissions and storage are all negotiated with the system, which grows stricter every year.

    Muhammad Afzal is a senior frontend engineer who has built production applications since 2021, and runs M/AFZAL.

    More from Systems

    26Glossary

    Every concept on the map.

    The concept map's 177 entries, grouped as on the map. Select a term to find it there.

    The platform
    Android platform
    The stack under every app: Linux kernel, hardware abstraction layer, Android Runtime, native libraries and the Java API framework.
    Linux kernel
    Schedules processes, manages memory and drivers, and enforces the user ID that sandboxes each app.
    Binder
    The kernel driver for calls between processes. Nearly every framework API call ends as a Binder transaction to a system service.
    Zygote
    A process started at boot with the framework preloaded. Every app process is forked from it and shares its memory copy-on-write.
    ART
    The Android Runtime: runs DEX bytecode through an interpreter, a JIT and ahead-of-time compiled code, with a concurrent garbage collector.
    system_server
    The process hosting the system services: activity, window, package and input managers, and dozens more.
    HAL
    The hardware abstraction layer: vendor drivers for camera, sensors and audio behind stable interfaces.
    App sandbox
    Each app runs as its own Linux user, in its own process, with private files no other app can read.
    SELinux
    Mandatory access control that confines every process, system ones included, to what its policy allows.
    SurfaceFlinger
    The system compositor. It combines the buffers of every visible window into the frame sent to the display.
    Low memory killer
    lmkd kills processes in order of importance when memory runs short. Cached background apps go first.
    Build and release
    Gradle
    The build system. It configures a graph of tasks from your build scripts and runs only those whose inputs changed.
    Android Gradle Plugin
    Adds the Android tasks to Gradle: merging manifests and resources, compiling, dexing, packaging and signing.
    Kotlin
    Android's preferred language since 2019, compiled by the K2 compiler to JVM bytecode before dexing.
    KSP
    Kotlin Symbol Processing. Runs code generators such as Room and Hilt at compile time, replacing kapt.
    Build variants
    One combination of a build type, such as debug or release, and product flavours.
    R8
    The release compiler. It shrinks, optimises and obfuscates code and emits DEX; keep rules protect reflected code.
    DEX
    Dalvik Executable, the register-based bytecode ART runs. D8 converts JVM class files into it.
    AAPT2
    Compiles and links resources, gives each an ID and generates the R class.
    Manifest
    AndroidManifest.xml declares components, permissions and capabilities. Library manifests merge into it.
    App Bundle
    The .aab file uploaded to Google Play, which builds and signs optimised APKs for each device.
    App signing
    Every APK is signed. With Play App Signing, Google holds the signing key and you sign uploads with an upload key.
    SDK levels
    minSdk is the oldest supported version, compileSdk the APIs you can call, targetSdk the behaviour you have opted into.
    Modules
    Separate Gradle projects, such as app, feature and core, that build in parallel and enforce boundaries.
    Google Play
    Distribution: testing tracks, staged rollouts, Android vitals and the yearly targetSdk requirement.
    Native code
    NDK
    The Native Development Kit: toolchains and headers for compiling C and C++ into an app's shared libraries.
    JNI
    The Java Native Interface, through which Kotlin calls C++ and C++ calls back into the runtime.
    CMake
    The native build system Gradle runs once for each ABI.
    ABI
    The CPU architecture a native library is compiled for; arm64-v8a on almost every current phone.
    16 KB pages
    Newer devices use 16 KB memory pages, and native libraries must be aligned for them to load.
    JNI references
    Local references die when the native call returns; global references live until you delete them.
    Permissions and security
    Permissions
    Declared in the manifest. Dangerous ones must also be granted by the user while the app runs.
    Run-time permission
    A permission the user grants in a system dialog, and can revoke at any time.
    Activity Result API
    Registers a contract for results from another activity or a permission request, safe across recreation.
    Photo picker
    A system screen that gives the app the media the user chose, with no storage permission.
    Keystore
    Keeps cryptographic keys in secure hardware, so key material never enters your process.
    BiometricPrompt
    System biometric authentication, which can be required before a Keystore key is used.
    Network security config
    XML that declares trusted certificate authorities, certificate pins and whether cleartext is allowed.
    Play Integrity API
    Lets your server check that a request comes from your genuine app on a genuine device.
    Notifications
    Messages posted to user-controlled channels; posting needs a run-time permission since Android 13.
    Performance
    Performance
    Start-up time, smooth frames and memory use, measured on real devices in release builds.
    Cold start
    Launch with no process: fork from Zygote, create the Application, create the activity, draw the first frame.
    Baseline Profiles
    Classes and methods shipped with the app so ART compiles them ahead of time at install.
    Macrobenchmark
    Measures start-up and scrolling on a device, and generates Baseline Profiles.
    Perfetto
    The system tracing tool: every thread, frame and Binder call on one timeline.
    Jank
    A frame that misses its deadline, so the previous frame stays on screen.
    LeakCanary
    Finds destroyed activities, fragments and ViewModels still in memory, and the references holding them.
    Garbage collector
    ART's concurrent collector frees unreachable objects with short pauses; heavy allocation still costs CPU.
    StrictMode
    A debug tool that flags disk and network access on the main thread, and leaked resources.
    App Startup
    Runs library initialisers through one content provider, in a declared order.
    App components
    App components
    Activities, services, broadcast receivers and content providers: the entry points the system can start.
    Activity
    One screen and its window; the system creates, pauses and destroys it.
    Service
    A component for work without a screen: started, bound or foreground.
    BroadcastReceiver
    Runs in response to a broadcast, such as boot completing or the time zone changing.
    ContentProvider
    Shares structured data through content:// URIs, and is created before Application.onCreate.
    Intent
    A message describing an operation. Explicit intents name the target; implicit ones describe an action.
    Intent filter
    A manifest declaration of the actions, categories and data a component handles.
    PendingIntent
    A token letting another process fire an intent later, as your app.
    Context
    The handle to resources, files, system services and starting components.
    Application
    The object created first in every app process, for process-wide setup.
    App Links
    URLs that open a specific screen. Verified App Links skip the chooser.
    Task and back stack
    A stack of activities the user sees as one app in Recents. Back pops the top one.
    Launch modes
    standard, singleTop, singleTask, singleInstance: whether a start creates an instance, and in which task.
    Lifecycle
    Lifecycle
    The states a component moves through, CREATED, STARTED, RESUMED, and the callbacks between them.
    LifecycleOwner
    Anything with a lifecycle that observers and coroutine scopes can attach to.
    Callbacks
    onCreate, onStart, onResume, onPause, onStop, onDestroy, called by the system on the main thread.
    Configuration change
    Rotation, dark mode, language or window size. By default the activity is destroyed and recreated.
    Process death
    The system kills a background process for memory; the user later returns to a recreated screen.
    Saved instance state
    A small Bundle kept by the system across recreation and process death.
    Edge-to-edge
    Drawing behind the system bars and applying insets yourself; enforced when targeting Android 15.
    OnBackPressedDispatcher
    Routes Back to registered callbacks, which predictive back depends on.
    Fragments
    Fragment
    A reusable portion of UI with its own lifecycle, hosted by an activity or another fragment.
    FragmentManager
    Adds, removes and replaces fragments, recreates them, and keeps their back stack.
    Fragment transaction
    A batch of fragment changes committed together, asynchronously by default.
    viewLifecycleOwner
    The lifecycle of a fragment's view, which is destroyed and recreated more often than the fragment.
    Fragment Result API
    Passes results between fragments through the FragmentManager instead of direct references.
    DialogFragment
    A fragment that shows a dialog and survives recreation, unlike a bare Dialog.
    Resources and configuration
    Resources
    Strings, layouts, drawables, colours and sizes kept outside code and chosen per configuration.
    Qualifiers
    Directory suffixes such as -night, -fr and -sw600dp that select alternative resources.
    dp and sp
    Density-independent units: dp keeps sizes physical across screens, sp also follows the user's font size.
    Themes and styles
    A theme applies attributes to a whole Context; a style applies them to one view.
    Material 3
    Google's design system for Android, with dynamic colour from the wallpaper since Android 12.
    Accessibility
    TalkBack, labels, 48 dp touch targets, and the semantics tree accessibility services read.
    Window insets
    The sizes of the system bars, keyboard and cut-outs that content must avoid.
    Testing
    Testing
    Local tests on the JVM and instrumented tests on a device, from single classes to whole journeys.
    Local tests
    JUnit tests in src/test that run on your computer in seconds.
    Robolectric
    Runs framework code on the JVM, so tests can create activities without a device.
    Espresso
    View-based UI tests that wait for the main thread to go idle before each step.
    Compose testing
    Finds nodes in the semantics tree and asserts on them, through a test rule.
    runTest
    Runs coroutine tests on virtual time, so delays complete instantly.
    Turbine
    A library for asserting on a Flow's emissions one at a time.
    Fakes
    Small working stand-ins, such as an in-memory repository, that replace real dependencies in tests.
    The main thread
    Main thread
    The one thread that handles input, lifecycle callbacks, layout and drawing.
    Looper
    A thread's loop: take the next message from the queue, dispatch it, repeat.
    MessageQueue
    The time-ordered queue a Looper drains; the thread sleeps in the kernel while it is empty.
    Handler
    Posts messages and runnables to one Looper's queue, now or later.
    Choreographer
    Runs each frame's work on vsync: input, then animation, then traversal.
    VSYNC
    The display's refresh signal: every 16.7 ms at 60 Hz, 8.3 ms at 120 Hz.
    RenderThread
    Turns recorded display lists into GPU commands, off the main thread.
    ANR
    Application Not Responding: the main thread failed to handle input within 5 seconds.
    Views
    View
    The original UI toolkit: a tree of objects that each measure, lay out and draw themselves.
    ViewGroup
    A View that contains children and decides where they go.
    Measure, layout, draw
    The three passes of a traversal: sizes, positions, then drawing commands.
    RecyclerView
    Shows long lists by reusing a few item views as they scroll off screen.
    DiffUtil
    Computes the smallest set of changes between two lists, so only those animate.
    View binding
    Generated classes with typed references to the views in an XML layout.
    ViewRootImpl
    Connects a window's view tree to the system: it receives input and schedules traversals.
    Jetpack Compose
    Jetpack Compose
    The declarative UI toolkit: functions describe the UI for the current state, and Compose keeps the screen in sync.
    @Composable
    A function that emits UI; the compiler plugin adds what Compose needs to track it.
    Recomposition
    Running again the composables that read changed state, and skipping the rest.
    State
    Observable values such as mutableStateOf. Reads are tracked; writes schedule recomposition.
    remember
    Keeps a value across recompositions; rememberSaveable keeps it across recreation too.
    Snapshot system
    Compose's transactional state store, which records which code read which state.
    Side effects
    LaunchedEffect, DisposableEffect and SideEffect: controlled ways to act outside composition.
    Modifier
    An ordered chain describing one element's layout, drawing and input.
    Lazy lists
    LazyColumn and LazyRow compose only the visible items, keyed for stable identity.
    Stability
    Whether Compose can trust a type's equality, which decides whether a composable can be skipped.
    CompositionLocal
    Values passed implicitly down the tree, such as the theme and the Context.
    Three phases
    Composition decides what, layout decides where, drawing decides how it looks.
    Coroutines
    Coroutines
    Kotlin's lightweight concurrency: code that suspends without blocking its thread.
    suspend
    Marks a function that may pause; the compiler turns its body into a state machine.
    Continuation
    The object holding where a suspended function resumes, and its local variables.
    CoroutineScope
    Owns coroutines. Cancelling the scope cancels everything launched in it.
    Job
    A coroutine's handle and lifecycle. Jobs form a tree of parents and children.
    SupervisorJob
    A job whose children can fail without cancelling their siblings or parent.
    Dispatchers
    Decide which threads run a coroutine: Main, Default for CPU work, IO for blocking calls.
    withContext
    Runs one block on another dispatcher and returns its result.
    Structured concurrency
    Every coroutine has a parent, none outlives its scope, and no failure is lost.
    Cancellation
    Cooperative: a coroutine stops at its next suspension point or isActive check.
    viewModelScope
    A scope cancelled when its ViewModel is cleared, on Main.immediate with a SupervisorJob.
    lifecycleScope
    A scope tied to an activity or fragment, cancelled when it is destroyed.
    Flow
    Flow
    A cold asynchronous stream: nothing runs until something collects it.
    StateFlow
    A hot flow that always holds one current value; the standard container for UI state.
    SharedFlow
    A hot flow that broadcasts to every collector, with optional replay.
    stateIn
    Turns a cold flow into a StateFlow shared within a scope.
    Channel
    A hot queue between coroutines; each element goes to one receiver.
    callbackFlow
    Wraps a callback API, such as location updates, in a Flow.
    repeatOnLifecycle
    Collects while the lifecycle is at least STARTED, and cancels when it stops.
    collectAsStateWithLifecycle
    Collects a flow into Compose state, only while the lifecycle is started.
    Operators
    map, filter, combine, flatMapLatest, debounce: transformations between producer and collector.
    Background work
    Background work
    Work that continues after the user leaves the screen, under strict system limits.
    WorkManager
    Persistent, guaranteed background work with constraints, retries and chaining.
    Foreground service
    A service the user can see through a notification, with a declared type since Android 14.
    JobScheduler
    The system scheduler that batches background jobs across apps.
    AlarmManager
    Fires a PendingIntent at a time; exact alarms need special permission.
    Doze
    Idle mode that defers jobs, alarms and network while the device is still and unplugged.
    App Standby Buckets
    Ranks apps by recent use and gives rarely used ones less background time.
    Bound service
    A service clients connect to and call, across processes through Binder.
    Storage
    Local storage
    App-private files, databases and preferences, plus shared media through MediaStore.
    Room
    An SQLite library with compile-time checked queries, suspend functions and Flow results.
    DAO
    The interface of annotated queries that Room generates an implementation for.
    Migrations
    Steps that move an existing database to a new schema without losing data.
    DataStore
    Asynchronous, transactional key-value or typed storage built on coroutines and Flow.
    SharedPreferences
    The older key-value store, whose blocking reads and flushed writes can stall the main thread.
    Scoped storage
    Since Android 10, apps see their own files plus media they create or the user picks.
    MediaStore
    The system index of shared photos, videos, audio and downloads.
    Networking
    Networking
    HTTP from the app, always off the main thread and over TLS by default.
    OkHttp
    The HTTP client under almost everything: connection pooling, HTTP/2, caching, interceptors.
    Retrofit
    Turns an annotated Kotlin interface into HTTP calls, with suspend support.
    Interceptors
    Links in OkHttp's chain that can read or rewrite every request and response.
    Serialization
    Converting JSON to and from Kotlin types, with kotlinx.serialization or Moshi.
    ConnectivityManager
    Reports which networks are available, through callbacks.
    Architecture
    App architecture
    A UI layer, an optional domain layer and a data layer, with dependencies pointing one way.
    ViewModel
    Holds screen state and logic; survives configuration changes, not process death.
    SavedStateHandle
    A key-value map in the ViewModel that survives process death.
    UI state
    One immutable object describing everything the screen shows.
    Unidirectional data flow
    State flows down to the UI; events flow up to the ViewModel.
    Repository
    The data layer's public face, hiding whether data comes from network, database or memory.
    Use case
    An optional domain class holding one piece of business logic shared by several ViewModels.
    Single source of truth
    Each piece of data has one owner, usually the database, and everything else observes it.
    Navigation
    Maps routes to destinations and manages the back stack, arguments and deep links.
    Dependency injection
    Dependency injection
    Classes receive their dependencies instead of creating them, so tests can swap them.
    Hilt
    Jetpack's injection library over Dagger, with components bound to Android lifecycles.
    Dagger
    Compile-time injection that generates the code building your object graph.
    Components
    Containers of bindings with a lifetime: Singleton, ViewModel, Activity and others.
    Scopes
    Annotations such as @Singleton that give one shared instance per component.
    Modules
    Classes telling Hilt how to provide interfaces and third-party types, with @Binds and @Provides.