Bookmarks
ReferenceMobile developmentVerified

Android and Kotlin

Android and Kotlin — the platform and language for mobile apps. In this reference: Jetpack Compose, coroutines, state, navigation, Room and publishing.

checked 1 Nov · next check 8 Nov · 49 min read

Sections
13
Reading
49 min
Current version
Kotlin 2.4.21; Compose 1.12.1; AGP 9.5.0
Written from
developer.android.com/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Android and Kotlin are and how they fit together

An Android app is a set of components that the system runs in a separate sandboxed process. You write it in Kotlin, which Google recommends for Android, and build the UI with Jetpack Compose. The code is split into at least two layers: a UI layer holding the state of the screens, and a data layer.

A native Kotlin app works directly with the platform APIs and the Jetpack (AndroidX) libraries. Kotlin also suits multiplatform projects (Kotlin Multiplatform), but this reference covers Android only. If one app is needed for both Android and iOS, the approaches are compared in the Flutter reference, the section “What Flutter is and how it works”.

What an app is made of

An Android app has no single entry point such as main(): the system creates the component it needs whenever the user, the system or another app addresses it. There are four kinds of components:

  • Activity — a screen with a UI and the user’s entry point into the app. A modern app usually has one, and it shows every Compose screen.
  • Service — work in the background with no UI, such as playing music.
  • BroadcastReceiver — a response to system events outside the app’s normal use, such as an alarm going off.
  • ContentProvider — gives other apps access to the app’s data over a URI.

Components are declared in the manifest, AndroidManifest.xml; permissions such as internet access and device requirements are listed there too. The system will not run an Activity, a Service or a ContentProvider that is missing from the manifest; a BroadcastReceiver can also be registered in code.

Every app runs in its own sandbox: by default it gets its own Linux user and its own process, and other apps cannot reach its files. The system starts the process when one of the components is needed and may kill it to free memory.

How app code is structured

Components are short-lived: an Activity is recreated when the screen is rotated, and the system may kill a background process. So neither data nor state is kept in components. The official architecture splits an app into at least two layers: the UI layer shows the data, the data layer holds the business logic and works with the sources. State flows from the data to the screen, events from the screen to the data.

A domain layer with use cases is added when the logic has to be reused across several ViewModels.

How Compose differs from View

FeatureJetpack ComposeView (XML)
How the UI is describedKotlin functions with the @Composable annotationXML layouts, from which a tree of widgets is built
How the screen updatesthe function runs again with new data — recompositioncode changes the widgets: findViewById(), setText()
Where the state livesin function parameters and state holdersinside each widget
LanguageKotlin onlyKotlin or Java
Interoperabilityembeds into a View screenembeds into a Compose screen

For a new screen choose Compose: the UI is described in code, starting from the data, and the widgets need no manual synchronisation. Existing View screens can be migrated gradually, one at a time, because the two systems embed into each other.

What to know beforehand

  • Basics of programming: variables, functions, classes. Kotlin as Android uses it — in the section “Kotlin syntax”.
  • The command line and environment variables — the Bash reference.
  • HTTP requests, methods and response codes — the HTTP and REST reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday Kotlin, Compose and coroutine constructs, plus Gradle and adb commands. The constructs are explained in detail in their own sections; replace the names in the examples (user, state, app-debug.apk) with your own.

Kotlin

TaskHow to write
A read-only and a mutable variableval name = "Aziz", var count = 0
Interpolate a value into a string"Привет, $name! Всего: ${list.size}"
A nullable typeval email: String? = null
Safe call and default valueemail?.length ?: 0
Run code if not nullemail?.let { send(it) }
A data class and a copy of itdata class User(val name: String), user.copy(name = "Aziz")
Selecting by valuewhen (x) { 0 -> "ноль"; else -> "много" }
A lambda as the last argumentlist.filter { it > 0 }
An extension functionfun String.shout() = uppercase() + "!"
A single-instance objectobject Config { val url = "https://example.com" }
Configure an object and return itStringBuilder().apply { append("Hi") }

Compose

TaskHow to write
Elements stacked verticallyColumn { Text("A"); Text("B") }
Elements in a rowRow { Text("A"); Text("B") }
Elements on top of each otherBox { Image(photo, null); Text("Новое") }
A long listLazyColumn { items(users, key = { it.id }) { Text(it.name) } }
Padding and widthModifier.padding(16.dp).fillMaxWidth()
State inside a functionvar on by remember { mutableStateOf(false) }
State that survives a rotationvar text by rememberSaveable { mutableStateOf("") }
State from a ViewModelval state by vm.uiState.collectAsStateWithLifecycle()
A coroutine while the composable is on screenLaunchedEffect(message) { host.showSnackbar(message) }

Coroutines and Flow

TaskHow to write
Launch a coroutine in a ViewModelviewModelScope.launch { repo.refresh() }
Move off the main threadwithContext(Dispatchers.IO) { file.readText() }
Two requests in parallelval a = async { loadA() }; val b = async { loadB() }
State for the UIprivate val _state = MutableStateFlow(UiState())
Expose it as read-onlyval state = _state.asStateFlow()
Update the state_state.update { it.copy(loading = true) }

Gradle and adb

TaskCommand
Build a debug APK./gradlew assembleDebug
Build and install on a device straight away./gradlew installDebug
Build an App Bundle for Google Play./gradlew bundleRelease
List the project’s tasks./gradlew tasks
Connected devicesadb devices -l
Install an APKadb install app-debug.apk
Install on a specific deviceadb -s emulator-5554 install app-debug.apk
Show only errors in the logadb logcat "*:E"
Stop the adb server; the next command starts it againadb kill-server

Section sources

the section is written from these pages

Installation and first run

The official way is to install Android Studio: the first-run wizard downloads the Android SDK for you. The installation has worked if a project from the Empty Activity template builds and runs on an emulator or a phone.

Linux

You need a 64-bit distribution with GNOME, KDE or Unity and glibc 2.31 or newer. Memory: at least 8 GB, and at least 16 GB with the emulator; the processor must support Intel VT-x or AMD-V virtualisation, and it must be enabled in the BIOS. Download the .tar.gz archive from the installation page, unpack it, for example into /opt/, and run studio from the bin directory.

bashLinux terminal
sudo tar -xzf android-studio-*-linux.tar.gz -C /opt/opt/android-studio/bin/studio

For 64-bit Ubuntu, the official instructions ask you to install the 32-bit libraries beforehand:

bashUbuntu
sudo apt-get install libc6:i386 libncurses5:i386 \  libstdc++6:i386 lib32z1 libbz2-1.0:i386

The first-run wizard offers to import your previous settings and downloads the Android SDK components. To get Android Studio into the applications menu, choose “Tools → Create Desktop Entry”. Updates are checked with “Help → Check for Update”.

macOS and Windows

On macOS (12 or newer) open the DMG image and drag Android Studio into “Applications”; support for Intel-based Macs is being phased out. On Windows (64-bit 10 or newer) run the .exe installer. Then comes the same first-run wizard.

First project

Choose “File → New → New Project”, the Empty Activity template and click “Next”. The “Language” field offers only Kotlin: Compose works with Kotlin alone. Set the name, the package name and the Minimum API level, then click “Finish”. Without Android Studio, the same project is created by the Android CLI:

bashterminal
android create empty-activity --name=MyApp

By default, Android Studio shows the project in the “Android” view. The actual tree on disk is visible in the “Project” view; the app module is called app by default:

text
MyApp/├── build.gradle.kts        build for the whole project└── app/                    app module    ├── build.gradle.kts    module build    └── src/        ├── main/        │   ├── AndroidManifest.xml        │   ├── java/       Kotlin and Java code        │   └── res/        strings, images        ├── test/           local unit tests        └── androidTest/    instrumented tests

Compose dependencies

The project keeps plugin and library versions in the version catalogue libs.versions.toml. Compose libraries are added through a BOM — a specification that sets matching versions for all Compose libraries: the version is written only on the BOM. The Compose compiler is added by the org.jetbrains.kotlin.plugin.compose plugin, whose version matches the Kotlin version.

kotlinapp/build.gradle.kts
android {    buildFeatures {        compose = true    }} dependencies {    val composeBom = platform("androidx.compose:compose-bom:2026.09.00")    implementation(composeBom)    implementation("androidx.compose.material3:material3")    // preview in Android Studio    implementation("androidx.compose.ui:ui-tooling-preview")    debugImplementation("androidx.compose.ui:ui-tooling")}

Running on an emulator and a phone

For the emulator, create a virtual device (AVD) in “Device Manager”, start it and click “Run”: Android Studio builds the app and installs it.

For a phone, open “Settings → Developer options” on the device and enable “USB debugging”, then connect the cable and confirm the computer’s RSA key request. On Windows, you may need the manufacturer’s USB driver. On Ubuntu, add yourself to the plugdev group and install the udev rules:

bashUbuntu
sudo usermod -aG plugdev $LOGNAMEsudo apt-get install android-sdk-platform-tools-common

The group takes effect after you sign in again. Check the connection: the phone should appear in the list printed by adb devices from the SDK’s platform-tools directory. Since Android 11, you can also debug over Wi-Fi: “Pair Devices Using Wi-Fi” in the run menu.

bashterminal
adb devices

Section sources

the section is written from these pages

Kotlin syntax

Android code in Kotlin needs val and var variables, functions, data classes, when, lambdas and types that allow null. The compiler infers types on its own and does not let you access a value that may be null without a check.

Variables and functions

val declares a read-only variable and var a mutable one. The type may be omitted: the compiler infers it from the value. Values are inserted into a string with the $name or ${expression} template. if is an expression and returns a value, and function parameters can have default values.

kotlinMain.kt
val name = "Dilnoza"var count = 0 // excited is optional: false by defaultfun greet(name: String, excited: Boolean = false): String {    val mark = if (excited) "!" else "."    return "Hello, $name$mark Letters in the name: ${name.length}"} // expression function: the return type is inferredfun square(x: Int) = x * x fun main() {    count += 1    println(greet(name))    println(square(count))}

Null safety

The String type cannot hold null, but String? can. You cannot access such a value directly. You need an if check, the safe call ?., which returns null instead of crashing, or the Elvis operator ?: with a value for the null case. After an if (x != null) check the compiler itself narrows the type to the non-null one.

kotlin
fun describe(email: String?): String {    // email.length without a check does not compile    val length = email?.length ?: 0    email?.let { println("Sending to $it") }    if (email != null) {        // here email is already String        println(email.uppercase())    }    return "Address length: $length"}

Classes, data class and object

A class’s properties are declared right in the primary constructor. Classes are closed for inheritance until marked open. A data class additionally gets equals(), hashCode(), toString(), copy() and componentN() — this is how data models and screen state are described. object declares a class that has exactly one instance.

kotlin
class Account(val owner: String, var balance: Long) data class User(val name: String, val age: Int) object AppConfig {    val baseUrl = "https://example.com"} fun main() {    val account = Account("Aziz", 0)    account.balance += 5_000     val user = User("Aziz", 20)    // a copy with a different age; user stays unchanged    val older = user.copy(age = 21)    println(older)    println(AppConfig.baseUrl)}

sealed and when

when is an expression too: each branch returns a value. If the subject is a sealed class or interface, the compiler knows all its subclasses and checks that every one of them is listed; the else branch is not needed. This is how Android describes mutually exclusive screen states: loading, data, error.

kotlinUiState.kt
sealed interface UiState {    data object Loading : UiState    data class Success(val items: List<String>) : UiState    data class Error(val message: String) : UiState} fun title(state: UiState): String = when (state) {    is UiState.Loading -> "Loading"    is UiState.Success -> "Found: ${state.items.size}"    is UiState.Error -> "Error: ${state.message}"}

enum class suits a set of constants: each constant exists as a single instance, while a sealed subclass can have many instances, each carrying its own data.

Lambdas and function types

A function can be passed as a value. Its type is written as (Int) -> Unit: parameters in brackets, the result after the arrow. A lambda is written in curly braces; when it is the last argument, it is moved outside the call brackets, and the single parameter is available as it. Event handlers are passed the same way in Compose.

kotlin
fun repeatTimes(times: Int, action: (Int) -> Unit) {    for (i in 1..times) {        action(i)    }} fun main() {    // the lambda is the last argument, so it goes outside the brackets    repeatTimes(3) { println("Step $it") }     val onClick: () -> Unit = { println("Clicked") }    onClick()}

Collections, extensions and apply

listOf creates a read-only list. Collections are processed in a chain of filter, sortedBy and map with lambdas. An extension function adds a method to an existing type without inheritance. ?.let runs the block only when the value is not null; apply configures an object and returns that same object; also performs an action and also returns the original object.

kotlin
fun String.shout() = uppercase() + "!" fun main() {    val prices = listOf(1200, 450, 3000)    val expensive = prices        .filter { it > 1000 }        .sortedBy { it }        .map { "$it UZS" }    println(expensive)    println("salom".shout())     val greeting = StringBuilder().apply {        append("Hello, ")        append("Android")    }    println(greeting)}

Section sources

the section is written from these pages

Coroutines and Flow

A coroutine is a computation that can suspend itself and resume later without blocking the thread. In Android, coroutines move long-running work — network, disk, calculations — off the main thread: otherwise the interface freezes and the system shows the “Application Not Responding” dialog.

suspend functions

A function marked suspend can suspend itself; you can call it only from a coroutine or another suspend function. While it waits for the network to respond, the thread is free for other work. suspend by itself does not move code to the background: that is what withContext with the right dispatcher does.

Scopes and structured concurrency

You launch a coroutine in a scope (CoroutineScope) that controls its lifetime. ViewModel provides a ready-made viewModelScope: it is cancelled when the ViewModel is destroyed, for example when the user leaves the screen, and all its coroutines are cancelled with it. This is structured concurrency: coroutines form a tree, the parent waits for its children to finish, and cancelling or failing a parent cancels all of its descendants.

A coroutine launched in GlobalScope is not part of such a tree, and the screen cannot cancel it.
kotlinProfileViewModel.kt
class ProfileViewModel(    private val repo: ProfileRepository) : ViewModel() {     fun load(userId: String) {        viewModelScope.launch {            // the two requests run in parallel            val user = async { repo.user(userId) }            val posts = async { repo.posts(userId) }            show(user.await(), posts.await())        }    }}
FunctionWhat it doesWhen to use it
launchlaunches a coroutine and returns no resultstart work without waiting for it
async and await()starts a computation and returns a Deferred — a future resultseveral independent requests in parallel
withContextruns a block on another dispatcher and returns the resultmove off the main thread
coroutineScopecreates a scope and waits for every coroutine launched in itparallel work inside a suspend function
runBlockingblocks the thread until the coroutines finishonly as a bridge from ordinary code, when there is no other way

Dispatchers and main-safety

A dispatcher decides which thread a coroutine runs on. Dispatchers.Main is the main UI thread, Dispatchers.IO is threads for input and output (network, disk), Dispatchers.Default is a shared pool for computations. Coroutines launched from viewModelScope without an explicit dispatcher run on the main thread.

The Android rule: a suspend function must be main-safe, that is, safe to call from the main thread. A class that does blocking work moves it off the main thread itself, with withContext, and takes the dispatcher as a constructor parameter so that tests can substitute a test one.

kotlinNewsRepository.kt
class NewsRepository(    private val api: NewsApi,    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO) {    // safe to call from the main thread    suspend fun fetchLatest(): List<Article> =        withContext(ioDispatcher) {            api.loadArticles()        }}

Cancellation and errors

Cancellation is cooperative: a coroutine stops only when it suspends or checks for cancellation itself. All the suspend functions from kotlinx.coroutines, such as delay and withContext, do this; in a long loop without them, call ensureActive(). An unhandled exception in a coroutine crashes the app, so catch the errors you expect inside the coroutine.

kotlin
fun refresh() {    viewModelScope.launch {        try {            repo.refresh()        } catch (e: IOException) {            _uiState.update { it.copy(error = "No network") }        }    }}

Flow: a stream of values

A Flow emits values one by one, as many times as needed, while a suspend function returns a single one. An ordinary flow is cold: the code of the flow { } builder does not run until someone starts collecting the flow, and every collector runs it afresh. The map and filter operators return a new flow, and collect starts the collection.

kotlin
fun ticks(): Flow<Int> = flow {    for (i in 1..3) {        delay(1_000)        emit(i)    }} suspend fun printTicks() {    ticks()        .map { it * 10 }        .collect { println(it) }}

StateFlow and SharedFlow

StateFlow is a hot flow that always keeps the current value in value; a new subscriber immediately receives the latest one. State is held in a private MutableStateFlow, and a read-only StateFlow is exposed to the outside. SharedFlow is a generalisation of StateFlow: it broadcasts values to all subscribers, and replay sets how many past values a new subscriber receives.

kotlinCounterViewModel.kt
class CounterViewModel : ViewModel() {    private val _count = MutableStateFlow(0)    val count: StateFlow<Int> = _count.asStateFlow()     fun increment() {        // update changes the value atomically        _count.update { it + 1 }    }}

A cold flow from a repository is turned into a StateFlow with the stateIn operator. The SharingStarted.WhileSubscribed() policy keeps the upstream active while there are subscribers.

kotlin
val news: StateFlow<List<Article>> = repo.newsStream    .stateIn(        viewModelScope,        SharingStarted.WhileSubscribed(),        emptyList()    )

Section sources

the section is written from these pages

Jetpack Compose: UI and layout

Jetpack Compose is a declarative UI toolkit for Android: the screen is described with Kotlin functions annotated with @Composable, which turn data into interface elements. When the data changes, Compose calls only the affected functions again — this is recomposition.

kotlinMainActivity.kt
class MainActivity : ComponentActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContent {            Greeting("Android")        }    }} @Composablefun Greeting(name: String) {    Text(text = "Hello, $name!")} @Preview@Composablefun GreetingPreview() {    Greeting("Compose")}

A composable function returns nothing: it describes what should be on the screen. The screen is attached to an Activity with a setContent { } call. @Preview shows the function in the Android Studio preview pane without running it on a device; you put it on a function that takes no parameters.

Recomposition rules

Recomposition skips functions whose parameters have not changed, and it can be cancelled and started again. The functions themselves may run in any order, in parallel, and often — as often as every frame of an animation. Hence the rules:

  • Keep composable functions fast and free of side effects: do not change shared variables in them and do not write to SharedPreferences
  • Do the heavy work — reading from disk, the network, sorting large lists — outside the function, in a coroutine, and pass the result as a parameter
  • Launch side effects from handlers such as onClick or through the effects API

The three phases of a frame

Every Compose frame goes through three phases: composition decides what to show, layout — where and how large, drawing — how to paint it. Compose remembers in which phase a piece of state was read and, when it changes, repeats that phase and, if needed, the ones after it. Layout walks the tree in a single pass: each element is measured once.

State read only during layout or drawing restarts those phases only.

So a value that changes on every frame, such as the scroll offset, is best read in a modifier lambda. The Modifier.offset { } lambda is called during the layout phase, and scrolling does not trigger recomposition.

kotlin
val listState = rememberLazyListState() Box {    Image(        painter = painterResource(R.drawable.header),        contentDescription = null,        // the offset is read during layout, not composition        modifier = Modifier.offset {            IntOffset(0, listState.firstVisibleItemScrollOffset / 2)        }    )    LazyColumn(state = listState) {        items(articles, key = { it.id }) { Text(it.title) }    }}

Column, Row and Box

Column arranges its children one below the other, Row side by side, Box on top of one another. Without a container several elements would end up at the same point and overlap. Gaps are made with Spacer and modifiers; how space is distributed is controlled by the verticalArrangement and horizontalArrangement parameters.

kotlinArticleRow.kt
@Composablefun ArticleRow(title: String, author: String) {    Row(modifier = Modifier.padding(8.dp)) {        Image(            painter = painterResource(R.drawable.avatar),            contentDescription = "Author avatar",            modifier = Modifier.size(40.dp).clip(CircleShape)        )        Spacer(modifier = Modifier.width(8.dp))        Column {            Text(text = title)            Text(text = author)        }    }}
ContainerHow it lays outExample
Columntop to bottoma form, a card
Rowleft to righta list row, buttons side by side
Boxin layers, one on top of anotheran icon over a picture
LazyColumntop to bottom, only the visible itemsa long list

Modifier: order matters

A modifier changes the size, padding, appearance and behaviour of an element. Modifiers are chained, and each one applies to the result of the previous one, so the order determines the result. In your own functions, accept a modifier: Modifier = Modifier parameter and pass it on to the first child element.

kotlin
// the whole area, including the padding, is clickableModifier.clickable(onClick = onClick).padding(16.dp) // the padding around the element is not clickableModifier.padding(16.dp).clickable(onClick = onClick)

fillMaxWidth() stretches the element to the full width the parent gives it, size() sets the desired size, and weight() in a Row or Column divides the free space in a given proportion.

Lists: LazyColumn

LazyColumn and LazyRow create and lay out only the visible items, which makes them suitable for long lists. The content is described with a DSL: item { } for a single item, items(list) { } for a collection. Pass a key — a stable unique key such as id: without one, an item’s state is tied to its position and is lost when items are reordered.

kotlin
LazyColumn(    contentPadding = PaddingValues(16.dp),    verticalArrangement = Arrangement.spacedBy(8.dp)) {    item { Text("News") }    items(articles, key = { it.id }) { article ->        ArticleRow(article.title, article.author)    }}

The Material 3 theme and Scaffold

The Empty Activity template creates the project theme based on MaterialTheme in the Theme.kt file of the ui.theme package: colours, typography and shapes. Wrap the screen in the theme and take values from it — MaterialTheme.colorScheme, MaterialTheme.typography; then the text and background colours adapt to the dark theme automatically.

Scaffold is the Material screen scaffold. Apply the padding it passes into its lambda to the content, for example with Modifier.padding or the contentPadding of a LazyColumn.

kotlin
// MyAppTheme is created by the template in ui/theme/Theme.ktMyAppTheme {    Scaffold { innerPadding ->        Text(            text = "Hello",            color = MaterialTheme.colorScheme.primary,            style = MaterialTheme.typography.titleSmall,            modifier = Modifier.padding(innerPadding)        )    }}

contentDescription labels, contrast and element sizes for assistive technologies are covered in the “Accessibility (a11y)” reference.

Section sources

the section is written from these pages

State and lifecycle

State is any value that changes over time and affects what is on the screen. In Compose you keep it in remember, rememberSaveable or a ViewModel; which one to choose depends on what the state has to survive: recomposition, a device rotation or the system killing the process.

remember and mutableStateOf

mutableStateOf creates an observable value: when it changes, Compose calls the functions that read it again. remember keeps an object across recompositions, but not across a configuration change such as a device rotation. For that there is rememberSaveable: it saves the value into a Bundle and restores it after the Activity and the process are recreated.

kotlinNameInput.kt
@Composablefun NameInput() {    var name by rememberSaveable { mutableStateOf("") }     Column(modifier = Modifier.padding(16.dp)) {        if (name.isNotEmpty()) {            Text("Hello, $name!")        }        OutlinedTextField(            value = name,            onValueChange = { name = it },            label = { Text("Name") }        )    }}

State hoisting

State hoisting makes a function stateless: instead of an internal variable it receives the current value and an event to change it. State flows down, events flow up — this is unidirectional data flow. Such a function is easier to reuse and to test.

kotlin
@Composablefun NameScreen() {    var name by rememberSaveable { mutableStateOf("") }    NameField(name = name, onNameChange = { name = it })} @Composablefun NameField(name: String, onNameChange: (String) -> Unit) {    OutlinedTextField(value = name, onValueChange = onNameChange)}

Where to hoist state to:

  • At the very least, to the nearest common ancestor of all the functions that read it
  • At the very least, to the highest place from which it is changed
  • Two states changed by the same event — together

ViewModel — the state of a screen

A ViewModel is a screen-level state holder: it holds the UI state and the business logic and survives configuration changes, so after a rotation the data is not loaded again. It lives as long as its owner does: an Activity — until it finishes, a navigation entry — while it stays on the back stack. Do not keep references to Context, Activity or Resources in a ViewModel: it outlives them.

kotlinCounterScreen.kt
data class CounterUiState(val count: Int = 0) class CounterViewModel : ViewModel() {    private val _uiState = MutableStateFlow(CounterUiState())    val uiState: StateFlow<CounterUiState> = _uiState.asStateFlow()     fun increment() {        _uiState.update { it.copy(count = it.count + 1) }    }} @Composablefun CounterScreen(viewModel: CounterViewModel = viewModel()) {    val uiState by viewModel.uiState.collectAsStateWithLifecycle()    Button(onClick = { viewModel.increment() }) {        Text("Pressed: ${uiState.count}")    }}

collectAsStateWithLifecycle() from the lifecycle-runtime-compose library collects a flow only while the screen is visible and turns it into Compose state; this is the recommended way to collect flows in Android. viewModel() from lifecycle-viewmodel-compose returns the ViewModel bound to the owner: after a rotation you get the same instance.

What survives a rotation and process death

The system recreates the Activity on a configuration change and may kill the app process while it is in the background. What each way of keeping state survives:

StorageRecompositionDevice rotationProcess death
rememberyesnono
rememberSaveableyesyesyes
ViewModelyesyesno
SavedStateHandle in a ViewModelyesyesyes

The Activity lifecycle

An Activity passes through the Created, Started and Resumed states and back again, and the system calls a callback on each transition. On a device rotation the Activity is destroyed and created again, so anything kept only inside it is lost.

From Stopped the screen returns through onRestart and onStart, from Paused — through onResume.
  1. onCreate() — the Activity is created: this is where you call setContent and get a ViewModel.
  2. onStart() — the screen becomes visible.
  3. onResume() — the screen is in the foreground and the user is interacting with it.
  4. onPause() — the first sign of leaving: the screen has lost focus but may still be visible in multi-window mode.
  5. onStop() — the screen is no longer visible; from here it can come back through onRestart() and onStart().
  6. onDestroy() — the Activity is finishing or being recreated because of a configuration change.

In Compose you do not need to override these methods to make the interface work: collectAsStateWithLifecycle collects the flows, and effects run code on lifecycle events.

Effects: LaunchedEffect and DisposableEffect

LaunchedEffect(key) starts a coroutine when the function enters the composition, cancels it on leaving and restarts it when the key changes. DisposableEffect is needed when the effect has to clean up after itself: the onDispose block at the end is required. To start a coroutine on a button press, use the scope from rememberCoroutineScope().

kotlin
@Composablefun ErrorSnackbar(error: String?, host: SnackbarHostState) {    // restarts on a new error    LaunchedEffect(error) {        if (error != null) {            host.showSnackbar(error)        }    }}

Section sources

the section is written from these pages

App architecture

The recommended Android architecture divides an app into a UI layer and a data layer, with a domain layer in between when you need one. State flows from the data to the screen, and events flow from the screen to the data: every kind of data has a single source of truth, and the code becomes easier to test.

Principles

  • Data only through a repository: screens and ViewModels never reach the database, the network or DataStore directly
  • A single source of truth: only the owner of the data changes it; for offline work the source of truth is the local database
  • Unidirectional data flow (UDF): the ViewModel provides state, and the UI reports user actions by calling functions
  • Immutable state: the UI state is an immutable data class that the UI only reads
  • Coroutines and Flow between layers: one-off actions are suspend functions, and data that changes over time is a Flow

The UDF cycle works like this: the ViewModel provides state to the UI, the UI reports a user action to the ViewModel, the ViewModel handles it, calls the repository and publishes new state. The cycle repeats for every event.

The screen does not change the UiState itself: it reports an event, and the ViewModel publishes the new state.

UI layer

The UI layer consists of UI elements — Compose functions — and state holders. For a screen the state holder is a ViewModel: it exposes a single uiState property of type StateFlow plus functions for events. Keep display logic — strings from resources, navigation, a snackbar — in the UI, and business logic in the ViewModel and the layers below.

kotlinNewsUiState.kt
data class NewsUiState(    val isLoading: Boolean = false,    val items: List<NewsItemUiState> = emptyList(),    val errorMessage: String? = null) data class NewsItemUiState(    val id: String,    val title: String,    val bookmarked: Boolean = false)

Events: handle them straight away

Pass a user event that needs business logic to the ViewModel by calling a function. Do not send an event that originates in the ViewModel itself to the UI as a separate signal: handle it straight away and reflect it in the UI state, for example with a “signed in” flag. That way the event is not lost when the screen rotates.

In lists do not pass the ViewModel down the function tree: give an item a lambda such as onItemClick, and call the ViewModel at the screen level.

Data layer

The data layer consists of repositories and data sources. You create a repository for each kind of data, such as NewsRepository and PaymentsRepository, while a data source works with one thing only: the network, a database or a file. A repository exposes immutable data, combines sources and resolves conflicts between them. It provides one-off operations as suspend functions and changes over time as flows.

Domain layer — when you need it

The domain layer consists of use cases — classes with a single operation, such as GetLatestNewsWithAuthorsUseCase. Add it when you need to reuse logic across several ViewModels or to simplify a complex ViewModel. A use case keeps no mutable data and is called like a function thanks to operator fun invoke.

Example: a news list

The repository exposes a flow of news from the database, the ViewModel turns it into screen state, and the screen only draws it:

kotlinNews.kt
class NewsRepository(private val dao: NewsDao) {    fun getNewsStream(): Flow<List<News>> = dao.observeAll()} private fun News.toUi() = NewsItemUiState(id = id, title = title) class NewsViewModel(repository: NewsRepository) : ViewModel() {    val uiState: StateFlow<NewsUiState> = repository.getNewsStream()        .map { news -> NewsUiState(items = news.map { it.toUi() }) }        .stateIn(            scope = viewModelScope,            started = SharingStarted.WhileSubscribed(5_000),            initialValue = NewsUiState(isLoading = true)        )} @Composablefun NewsScreen(viewModel: NewsViewModel) {    val uiState by viewModel.uiState.collectAsStateWithLifecycle()    LazyColumn {        items(uiState.items, key = { it.id }) { item ->            Text(item.title)        }    }}

Pass dependencies through the constructor, as with NewsRepository in the example: in tests you replace them with fakes. A simple app gets by with manual dependency injection; once there are many screens with ViewModels, use Hilt.

Official recommendations

RecommendationStrength
Separate data layer and UI layerstrongly recommended
Data only through a repositorystrongly recommended
Coroutines and Flow between layersstrongly recommended
Unidirectional data flowstrongly recommended
Lifecycle-aware state collection: collectAsStateWithLifecyclestrongly recommended
Do not send events from the ViewModel to the UIstrongly recommended
A single Activity and Navigation 3strongly recommended
Jetpack Compose for new appsstrongly recommended
ViewModels without references to Context or Activitystrongly recommended
Dependency injection through the constructorstrongly recommended
Domain layerrecommended for large apps
Hiltrecommended
ViewModel instead of AndroidViewModelrecommended
A single uiState property on the ViewModelrecommended

Section sources

the section is written from these pages

Data: network, Room and DataStore

Network requests run off the main thread, data for offline use is kept in a Room database, and settings go into DataStore. All three sources are hidden behind a repository in the data layer, and the rest of the code never knows where the data came from.

Network

Requests require the INTERNET permission in the manifest. Android forbids network requests on the main thread and throws NetworkOnMainThreadException, so run them in a coroutine with Dispatchers.IO, or through a library with a suspend API.

xmlAndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

The platform ships with the HttpsURLConnection client. Higher-level APIs come from third-party libraries: Retrofit describes an API with an annotated interface, Ktor is JetBrains’ coroutine-based HTTP client. Wrap network calls in a repository:

kotlinUserRepository.kt
interface UserService {    @GET("/users/{id}")    suspend fun getUser(@Path("id") id: String): User} class UserRepository(private val userService: UserService) {    suspend fun getUserById(id: String): User =        userService.getUser(id)}

JSON: kotlinx.serialization

JSON in Kotlin is handled by kotlinx.serialization: add the org.jetbrains.kotlin.plugin.serialization plugin and the kotlinx-serialization-json library, then annotate the class with @Serializable.

kotlin
@Serializabledata class User(val id: String, val name: String) fun parse(body: String): User =    Json.decodeFromString(User.serializer(), body) fun toJson(user: User): String =    Json.encodeToString(User.serializer(), user)

Room: local database

Room is a layer on top of SQLite that checks SQL queries at compile time. Use it instead of working with SQLite directly. Three parts: the @Entity entity is a table, the @Dao DAO holds the query functions, and the @Database class is the entry point to the database.

Room 3 lives in the androidx.room3 package, generates Kotlin code only and requires KSP. All operations are coroutine-based: DAO functions must be suspend unless they return Flow, and building the database requires a SQLite driver.

kotlinapp/build.gradle.kts
dependencies {    val room_version = "3.0.3"    implementation("androidx.room3:room3-runtime:$room_version")    ksp("androidx.room3:room3-compiler:$room_version")}
kotlinAppDatabase.kt
@Entitydata class Note(    @PrimaryKey val id: Int,    val text: String) @Daointerface NoteDao {    // The flow reports every change to the table    @Query("SELECT * FROM note ORDER BY id DESC")    fun observeAll(): Flow<List<Note>>     @Insert    suspend fun insert(note: Note)     @Delete    suspend fun delete(note: Note)} @Database(entities = [Note::class], version = 1)abstract class AppDatabase : RoomDatabase() {    abstract fun noteDao(): NoteDao}
kotlin
val db = Room.databaseBuilder<AppDatabase>(applicationContext, "app.db")    .setDriver(AndroidSQLiteDriver())    .build()

A database instance is expensive: in a single-process app, create it once. For migrations, the Room Gradle Plugin exports database schemas to the directory set in schemaDirectory, usually schemas. Keep these files in the code repository: automatic migrations are checked against and built from them.

DataStore: settings

DataStore stores key–value pairs (Preferences DataStore) or typed objects asynchronously and transactionally, on coroutines and Flow. Use it instead of SharedPreferences. There must be exactly one instance per file in a process: declare it once, at the top level of a Kotlin file.

kotlinSettings.kt
val Context.dataStore: DataStore<Preferences> by    preferencesDataStore(name = "settings") val DARK_THEME = booleanPreferencesKey("dark_theme") fun darkThemeFlow(context: Context): Flow<Boolean> =    context.dataStore.data.map { it[DARK_THEME] ?: false } suspend fun setDarkTheme(context: Context, enabled: Boolean) {    context.dataStore.updateData { prefs ->        prefs.toMutablePreferences().also {            it[DARK_THEME] = enabled        }    }}

What to store where

DataWhere to store itWhy
Structured data, cache for offline useRoomSQL queries, compile-time checks, Flow for changes
Settings and flags: key–value pairsPreferences DataStoreschema-free keys, asynchronous
A settings object with a defined schemaDataStore with a serializer: JSON or Protocol Bufferstype safety and transactional updates

Network security

Send all traffic over HTTPS and pass as little of the user’s personal data over the network as possible. Since Android 9 (API 28), unencrypted HTTP is blocked by default. If HTTP is unavoidable, for example for a test server, allow it only for the domain you need in the network security configuration:

xmlres/xml/network_security_config.xml
<network-security-config>    <domain-config cleartextTrafficPermitted="true">        <domain includeSubdomains="true">test.example.com</domain>    </domain-config></network-security-config>

The file is attached with the android:networkSecurityConfig="@xml/network_security_config" attribute on the <application> element in the manifest.

Section sources

the section is written from these pages

Signing and publishing to Google Play

For Google Play you build a release version in the Android App Bundle (AAB) format, sign it with your upload key and upload it to Play Console. Google Play builds and signs the APKs for each device itself. Before uploading, check the version number, R8 optimisation and the target API level.

Preparing the release version

The application ID applicationId cannot be changed after publication — choose it early. versionCode is a positive integer: the system and Google Play use it to tell which version is newer and refuse to install an older one over a newer one. Each release gets a higher versionCode; Play Console will not accept one that has already been used, and the maximum is 2,100,000,000. versionName is the string the user sees.

kotlinapp/build.gradle.kts
android {    namespace = "com.example.notes"    compileSdk = 37     defaultConfig {        applicationId = "com.example.notes"        minSdk = 24        targetSdk = 36        versionCode = 7        versionName = "1.4.0"    }     buildTypes {        release {            isDebuggable = false            // R8: shrinking and optimisation, AGP 9.3 and newer            optimization {                enable = true            }        }    }}

Before release, remove Log calls and debug tracing (startMethodTracing()) from your code and check the permissions in the manifest. Test the release build on at least one phone and one tablet.

App Bundle and Play App Signing

An App Bundle (.aab) is a format for publishing, not for installing: Google Play builds APKs from it for each device and signs them. Apps created in Google Play since August 2021 must use Play App Signing. Google holds the app signing key, and you sign the uploaded bundle with your upload key.

If the upload key is lost or stolen, it is reset through Play Console: the app signing key stays with Google and updates keep coming out. Google Play will not accept a build signed with a debug key.

Upload key

Create the key in Android Studio: “Build → Generate Signed Bundle/APK”, the “Android App Bundle” option, the “Create new” button under the keystore path. A keystore is a .jks file. The key must be valid for at least 25 years, and for Google Play it must not expire before 22 October 2033.

To have Gradle sign the release build itself and keep the passwords out of the repository, put them in a keystore.properties file in the project root:

propertieskeystore.properties
storePassword=change-mekeyPassword=change-mekeyAlias=uploadstoreFile=/home/aziz/keys/upload.jks
kotlinapp/build.gradle.kts
import java.io.FileInputStreamimport java.util.Properties val keystorePropertiesFile = rootProject.file("keystore.properties")val keystoreProperties = Properties()keystoreProperties.load(FileInputStream(keystorePropertiesFile)) android {    signingConfigs {        create("release") {            keyAlias = keystoreProperties["keyAlias"] as String            keyPassword = keystoreProperties["keyPassword"] as String            storeFile = file(keystoreProperties["storeFile"] as String)            storePassword = keystoreProperties["storePassword"] as String        }    }    buildTypes {        release {            signingConfig = signingConfigs.getByName("release")        }    }}

R8: shrinking and optimisation

R8 removes unused code and resources, shortens class and method names and rewrites code for speed: the app gets smaller, starts faster and hits ANR less often. Enable it for release builds only: optimisation lengthens the build and makes debugging harder.

From AGP 9.3, R8 is enabled with the optimization { enable = true } block, as in build.gradle.kts at the start of the section. Keep rules go into files with the .keep extension in the src/main/keepRules/ directory. In AGP before 9.3, isMinifyEnabled = true and isShrinkResources = true are used instead of the block.

Target API level

From 31 August 2026, new apps and updates on Google Play must have a targetSdk of at least 36 (Android 16). For Wear OS and Android Automotive OS the threshold is 35, and for Android TV and Android XR it is 34. On request the deadline was extended to 1 November 2026. Existing apps with a targetSdk below 35 are not shown to new users on devices running a newer version of Android.

When raising targetSdk, check the behaviour changes of every Android version between the old and the new value. Many of them only take effect when the app targets that version.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with Logcat: “View → Tool Windows → Logcat”. The query package:mine level:ERROR keeps only your app’s errors, while is:crash keeps crashes only. The exception is shown with a stack trace, where the lines from your own code are links.

How to check

  1. Reproduce the problem on an emulator or a phone with Logcat open.
  2. Find a crash with the is:crash query, and a hang by the ANR dialog.
  3. Read the exception type and the first line of the trace that comes from your own code.
  4. If your own code is not in the trace, check the arguments you passed to the asynchronous API calls.

FATAL EXCEPTION: main

Cause: an unhandled exception; the system terminates the process and shows a dialog saying that the app has stopped. In the trace, the exception line names its type, and the line beneath gives the class, method, file and line number where it occurred.

textexample output
AndroidRuntime: FATAL EXCEPTION: mainProcess: com.example.notes, PID: 3686java.lang.NullPointerException    at com.example.notes.MainActivityKt.lambda$0(MainActivity.kt:27)...
  • Open the first trace line from your own package — in Logcat it is a link to the code
  • In Kotlin, a NullPointerException usually comes from !! or from Java code: check values with ?. and ?:
  • Reproduce OutOfMemoryError on a virtual device with a small amount of memory

Application Not Responding (ANR)

Cause: the main thread is busy for too long — for example, the app did not respond to a tap within 5 seconds. Usually this is input/output or long computations on the main thread, waiting on a lock, or a deadlock.

bashemulator or rooted device
adb rootadb shell ls /data/anr
  • Move network and disk work into withContext(Dispatchers.IO) inside a ViewModel or repository
  • Do not do heavy list processing in a composable function: it runs on every recomposition; prepare the data in the ViewModel
  • Replace locks with Mutex.withLock: it suspends the coroutine instead of blocking the thread
  • Enable “Show all ANRs” in “Developer options” to see ANRs from background receivers as well

Failed to apply plugin 'org.jetbrains.kotlin.android'

Cause: the project has moved to AGP 9, where Kotlin support is built in, but the module still applies the org.jetbrains.kotlin.android plugin. The message The 'org.jetbrains.kotlin.android' plugin is no longer required for Kotlin support since AGP 9.0. has the same cause.

kotlinapp/build.gradle.kts
plugins {    // remove this line from the modules’ build.gradle.kts    alias(libs.plugins.kotlin.android)}
  • Remove the plugin from the modules’ build.gradle.kts, from the root build.gradle.kts and from the version catalog gradle/libs.versions.toml
  • kotlin-kapt is incompatible with built-in Kotlin: move to KSP, or temporarily to com.android.legacy-kapt
  • Replace the android.kotlinOptions {} block with kotlin { compilerOptions { } }
  • You can temporarily restore the old behaviour with the line android.builtInKotlin=false in gradle.properties; AGP 10 will not offer this option

The phone is not visible in Android Studio

Cause: USB debugging is off on the phone, the computer’s RSA key has not been confirmed, or on Linux the user lacks permissions for the USB device. Check whether adb sees the device:

bashterminal
adb devices
  • Enable “USB debugging” in “Developer options” and confirm the RSA key prompt on the phone: without it, adb commands do not run
  • In Ubuntu, add the user to the plugdev group, install the udev rules from the android-sdk-platform-tools-common package and log in again
  • Run “Tools → Troubleshoot Device Connections”: the assistant checks USB and restarts the ADB server
  • Try a different cable or a different device; on Windows, install the manufacturer’s USB driver

Minor issues

SymptomCauseWhat to do
Logcat shows too many messages from other processesall processes on the device are visiblethe package:mine query, and level:WARN if needed
Logs seem to have stopped after a restartthe app process exited and started againlook for the PROCESS ENDED and PROCESS STARTED markers in Logcat
UnknownHostException on a phoneno network — a normal situation, not a code errorhandle network exceptions; to check, use airplane mode
The screen stutters when settings are readreading from disk on the main thread, for example SharedPreferencesread the data in a ViewModel or repository via Dispatchers.IO
Wi-Fi debugging does not connectthe computer and the phone are on different networks, or Android is below 11one network, Android 11 or newer, up-to-date SDK Platform Tools

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Kotlin 2.4 and Jetpack Compose 1.12 on Android 17 (API 37). The latest Kotlin release is 2.4.21, dated 8 October 2026. A language release of Kotlin (2.x.0) comes out every six months; the tooling release (2.x.20) follows three months later.

ProductBranchLatest releaseSupport and requirements
Kotlin2.42.4.21, 8 October 2026the JVM standard library is supported until 3 December 2027; the branch was released on 3 June 2026
Jetpack Compose1.121.12.1, 9 September 2026in beta — the next branch is 1.13
Android Gradle Plugin9.59.5.0, October 2026requires Gradle 9.6.0 or newer and JDK 17 or newer; supports API up to 37
Android17API 37behaviour changes affect apps with targetSdk 37

Since Kotlin 2.4.0, each line of the standard library for the JVM is supported for 18 months. If a vulnerability is found, a fix is released for the latest release of the line and for every line within that window.

What changed in Kotlin 2.4

  • Kotlin syntax: context parameters and explicit backing fields are now stable; experimental collection literals [1, 2, 3] are enabled with the -Xcollection-literals flag
  • Installation and first run: the K1 compiler is no longer supported, and -language-version=1.9 does not work
  • Installation and first run: the minimum supported Android Gradle plugin version is 8.5.2. Kotlin 2.4.0 is fully compatible with Gradle from 7.6.3 to 9.5.0; it works with newer Gradle too, but deprecation warnings are possible

What changed in Compose 1.12

  • Installation and first run: the Compose libraries are built against compileSdk 37, so the project needs compileSdk 37 and Android Gradle plugin 9.2 or newer
  • State and lifecycle: SideEffect gained an overload with keys — a one-off effect without LaunchedEffect and DisposableEffect
  • Jetpack Compose: the new SlotTable implementation for faster recomposition, introduced in 1.11, is still experimental and is enabled by the ComposeRuntimeFlags.isLinkBufferComposerEnabled flag

What changes with targetSdk 37

  • Data: Certificate Transparency is enabled by default
  • Data: working with devices on a local network requires the ACCESS_LOCAL_NETWORK permission or the system device picker dialog
  • Data: TLS connections use ECH when both the networking library and the server support it; the mode is set by the <domainEncryption> element in the network security configuration
  • Jetpack Compose: on large screens (sw ≥ 600dp) the system ignores app-set restrictions on orientation, window size and aspect ratio, and this can no longer be turned off
  • Common errors and diagnostics: attempting to modify a static final field through reflection throws IllegalAccessException

Deprecated and removed

  • Android 17: ContentCaptureManager.setContentCaptureEnabled() is deprecated, and with targetSdk 37 calling it with false no longer disables Content Capture; use the FLAG_SECURE window flag instead
  • Android 17: launching an Activity from the background via IntentSender is restricted more strictly — instead of the MODE_BACKGROUND_ACTIVITY_START_ALLOWED constant, use MODE_BACKGROUND_ACTIVITY_START_ALLOW_IF_VISIBLE
  • Kotlin 2.4: the Compose compiler flags StrongSkipping and IntrinsicRemember now produce an error because these modes are enabled by default; they will be removed in Kotlin 2.5.0
  • Kotlin 2.4: the OptimizeNonSkippingGroups and PausableComposition flags are deprecated and will be removed in Kotlin 2.6.0

How to upgrade

  1. Kotlin: change the Kotlin version in the build together with the Compose compiler plugin version (the section “Installation and first run”) and check whether the kotlinx libraries need updating as well.
  2. Android Gradle Plugin 9.5: upgrade Gradle to 9.6.0 and check that the build runs on JDK 17 or newer.
  3. targetSdk 37: go through the list “What changes with targetSdk 37” and test the app.
  4. Compose: change the BOM version as described in the section “Installation and first run”, and check compileSdk and the AGP version.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 2 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Android and Kotlin” topic
13 sections
Another reference · Mobile development

iOS and Swift

Verified 1 Nov
All references · 61