Web & Mobile Development

Android Fundamentals: Activities, Compose, Architecture and Background Work

Beginner9 min readUpdated

Android has accumulated two decades of APIs, and the hard part for a newcomer is knowing which ones still represent the recommended path. This guide walks through a modern app from the Gradle build and the manifest to the activity lifecycle, Jetpack Compose, the ViewModel and repository layers, coroutines and Flow, storage, networking and the runtime permission model.

What you will learn

  • Navigate an Android project — Gradle modules, the manifest, resources and source sets
  • Explain the activity lifecycle and survive configuration changes and process death
  • Build screens with Jetpack Compose and read the XML layouts you will still inherit
  • Structure an app with a ViewModel, a repository and unidirectional state flow
  • Run work off the main thread with coroutines and schedule deferrable work reliably
  • Request runtime permissions and choose an appropriate storage option

Android development has an unusual learning curve: the platform is old enough that almost every problem has three documented solutions, one recommended, one legacy and one deprecated. A newcomer searching for how to load data or navigate between screens will find answers spanning fifteen years of API design, with nothing in the result to indicate which era it belongs to. Knowing the current recommended path is most of the battle.

This guide follows one path from end to end: how a project is assembled, what the operating system expects from your components, how to draw a screen with Jetpack Compose, and how to arrange the code so that data flows in one direction and survives the interruptions the platform will throw at it. Examples are Kotlin, which is the default language for Android and the one all current documentation uses.

What a project is made of

An Android project is a Gradle build. The root holds settings and version definitions, and each module has its own build script; the default module is app.

// app/build.gradle.kts
android {
    namespace = "com.example.orders"
    compileSdk = 36

    defaultConfig {
        applicationId = "com.example.orders"
        minSdk = 26
        targetSdk = 36
        versionCode = 14
        versionName = "2.3.0"
    }

    buildFeatures { compose = true }
}

dependencies {
    implementation(libs.androidx.activity.compose)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.room.runtime)
}

Three SDK numbers do different jobs and are routinely confused. compileSdk is the API level your code compiles against — set it to the newest available. minSdk is the oldest version the app installs on, which decides how much of the modern API you can use without guards. targetSdk is a declaration that you have tested against a given release; the system applies behaviour changes for that level and keeps compatibility shims for anything newer, and app stores require it to stay recent. The libs. references come from a version catalog in gradle/libs.versions.toml, which is the current way to keep dependency versions in one place across modules.

The manifest declares to the operating system what the app contains and what it needs:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".OrdersApplication"
        android:icon="@mipmap/ic_launcher"
        android:theme="@style/Theme.Orders">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Every activity, service, broadcast receiver and content provider must be declared here, along with permissions and any hardware requirements. An intent-filter advertises what a component can handle — the one above is what puts an icon in the launcher, and others let your app appear in the share sheet or open a particular category of link.

Activities and the lifecycle

An activity is a single entry point into your app: a screen the system can start, stop, recreate or kill. Most modern apps use a single activity that hosts many composable or fragment destinations rather than one activity per screen.

The lifecycle exists because your app does not control when it runs. A call arrives, the user switches apps, the device rotates, memory runs low. The callbacks are onCreate, onStart, onResume, onPause, onStop, onDestroy, and the pairing is symmetric: whatever you acquire in onStart you release in onStop.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent { OrdersApp() }
    }
}

Two consequences shape everything else. First, a configuration change — rotation, dark mode, locale, entering split screen — destroys and recreates the activity so resources for the new configuration can be loaded. Anything stored in an activity field is gone. Second, when your app is in the background the system may kill the process entirely and later restore it with the user expecting to be where they left off.

The answer to the first is the ViewModel, which is scoped to the screen and survives recreation. The answer to the second is SavedStateHandle or rememberSaveable, which persist a small amount of state through process death into a Bundle. Blocking rotation in the manifest is not a solution; it only hides one of many triggers.

Intents, and moving between screens

An intent is a message describing something to be done. An explicit intent names the target component and is how you start your own activity. An implicit intent describes an action and lets the system offer whichever installed app can handle it.

// Explicit
startActivity(Intent(this, DetailActivity::class.java).putExtra("orderId", id))

// Implicit — whichever app handles a web address
startActivity(Intent(Intent.ACTION_VIEW, "https://example.com/orders/$id".toUri()))

For results from another app — picking a photo, taking a picture, requesting a permission — use the Activity Result APIs with registerForActivityResult, which handle the recreation problem correctly. Inside a single-activity app, navigation between screens is handled by the Navigation component: destinations are declared in a graph, arguments are typed, and the back stack is managed for you rather than by juggling activities. Fragments predate composables as the reusable-screen unit and remain common; they have their own lifecycle, offset from the host activity's, and a separate lifecycle for their view, which is the source of most fragment bugs.

Drawing the screen

Two UI toolkits coexist. The View system describes a hierarchy in XML and inflates it at runtime; it is what the overwhelming majority of existing apps use and what you will read in any established codebase.

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/reference"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?attr/textAppearanceTitleMedium" />
</androidx.constraintlayout.widget.ConstraintLayout>

Jetpack Compose is the recommended toolkit for new work. Instead of describing a tree and mutating it, you write functions that turn state into UI, and the framework re-invokes those functions when the state they read changes.

@Composable
fun OrderRow(order: Order, onRemove: (String) -> Unit, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier.fillMaxWidth().padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(Modifier.weight(1f)) {
            Text(order.reference, style = MaterialTheme.typography.titleMedium)
            Text(order.formattedTotal, style = MaterialTheme.typography.bodySmall)
        }
        IconButton(onClick = { onRemove(order.id) }) {
            Icon(Icons.Default.Delete, contentDescription = "Remove order")
        }
    }
}

Three conventions carry most of the learning. State that a composable owns is held with remember { mutableStateOf(...) }, or rememberSaveable when it must survive recreation. State that several composables need is hoisted upward until it sits at their nearest common ancestor, so that children take a value and a callback and stay reusable and previewable. And every composable that renders anything should accept a Modifier parameter as its first optional argument, so the caller controls sizing, padding and click behaviour.

Accessibility deserves attention here for the same reasons it does on the web: contentDescription is the equivalent of alt text, touch targets should be at least 48dp, and the same principles discussed in HTML essentials apply to a phone screen.

Resources, configuration and localisation

Everything that is not code lives under res/: values/strings.xml, drawable/, mipmap/ for launcher icons, layout/ for XML, font/, and theme definitions. The directory name can carry qualifiers, and the system picks the best match at runtime — values-fr/ for French, values-night/ for dark mode, drawable-hdpi/ for a density, values-sw600dp/ for larger screens. This is why hardcoding a user-visible string is a genuine defect: it makes the app untranslatable, and lint will flag it.

Use dp for lengths so that a layout occupies the same physical size on any density, and sp for text so it respects the user's font size preference. Since API level 35, apps draw edge to edge by default, so you must apply window insets rather than assuming a rectangle free of system bars.

Lists

Lists are the workhorse of mobile UI, and both toolkits recycle views so that a thousand-item list costs no more than a screenful. In the View system this is RecyclerView, which needs an adapter, a ViewHolder that caches the item's view references and a LayoutManager; ListAdapter with a DiffUtil.ItemCallback computes the minimal set of changes between two lists so items animate correctly. In Compose the same behaviour is built in:

LazyColumn(contentPadding = PaddingValues(vertical = 8.dp)) {
    items(orders, key = { it.id }) { order ->
        OrderRow(order = order, onRemove = viewModel::remove)
    }
}

The key is the equivalent of the diff callback: it tells Compose which item is which across recompositions, so state and animations follow the right row. Omitting it on a reorderable list produces the same category of bug it does in any list-diffing framework.

Architecture: state in one direction

The recommended architecture is three layers. The UI layer — composables plus a ViewModel — renders state and forwards events. The domain layer is optional and holds use cases when business logic would otherwise be duplicated. The data layer holds repositories, each owning one type of data and deciding between local and remote sources.

data class OrdersUiState(
    val orders: List<Order> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
)

class OrdersViewModel(private val repository: OrderRepository) : ViewModel() {
    private val _state = MutableStateFlow(OrdersUiState(isLoading = true))
    val state: StateFlow<OrdersUiState> = _state.asStateFlow()

    init { refresh() }

    fun refresh() = viewModelScope.launch {
        _state.update { it.copy(isLoading = true, error = null) }
        runCatching { repository.load() }
            .onSuccess { orders -> _state.update { it.copy(orders = orders, isLoading = false) } }
            .onFailure { e -> _state.update { it.copy(error = e.message, isLoading = false) } }
    }
}

The flow is one-directional: the repository produces data, the ViewModel folds it into a single immutable state object, the UI renders that object, and user actions travel back as function calls. A single state class rather than several independent flags is what prevents impossible combinations such as loading and error being true at once. The ViewModel must not reference a view, a context or an activity — that is what causes memory leaks — and the UI collects the flow in a lifecycle-aware way so collection stops when the screen is not visible.

Coroutines, and work that must survive

The main thread renders the UI, so anything slow on it produces jank or a not-responding dialog. Kotlin coroutines are the standard answer: suspending functions release the thread while waiting instead of blocking it.

class OrderRepository(private val api: OrderApi, private val dao: OrderDao) {
    suspend fun load(): List<Order> = withContext(Dispatchers.IO) {
        val fresh = api.fetchOrders()
        dao.replaceAll(fresh)
        fresh
    }

    fun observe(): Flow<List<Order>> = dao.observeAll()
}

viewModelScope cancels its coroutines automatically when the ViewModel is cleared, which is what stops a request from outliving the screen that asked for it. Dispatchers.IO is for blocking calls, Dispatchers.Default for CPU work, and the main dispatcher for anything touching the UI. Flow carries streams of values over time and StateFlow always holds a current one, which is why it fits screen state so well. If you come from the thread and executor model described in Java concurrency, coroutines are structured concurrency over that same machinery, with cancellation that actually propagates.

Work that must complete even if the user leaves the app — uploading a queued form, syncing overnight — belongs to WorkManager, which persists the request, applies constraints such as "only on unmetered network while charging", retries with backoff and survives reboots. Do not use it for anything the current screen is waiting on.

Networking, storage and permissions

Most apps talk to an HTTP API, typically with Retrofit or Ktor over OkHttp, and serialise JSON with kotlinx.serialization or Moshi. Define the API as an interface of suspending functions, keep the wire models separate from your domain models, and map between them in the repository so a backend change does not ripple through the UI. Handle status codes deliberately rather than treating everything non-2xx as one failure — the distinctions in the HTTP status code reference map directly onto retry, re-authenticate and show-a-message, and the server-side contract is covered in REST API design.

For storage, the options are: DataStore for key-value preferences, which replaces the older SharedPreferences and is asynchronous and type-safe; Room for structured local data, a compile-time-checked SQL layer that returns Flow so the UI updates when the table does; the app-private files directory for documents and caches; and the MediaStore or the system photo picker for shared media. Nothing sensitive belongs in plain preferences — use the Keystore for keys and credentials.

Permissions are declared in the manifest and, for anything the system considers dangerous — location, camera, microphone, contacts, notifications — must also be granted by the user at runtime through the Activity Result API. Request them at the moment the feature is used rather than at launch, explain why before asking when the reason is not obvious, and handle refusal as a normal path rather than an error. The platform keeps narrowing what an app can reach without asking, so prefer the APIs that need no permission at all: the photo picker instead of storage access, and the document picker instead of file paths.

Key takeaways

  • An Android project is a Gradle build with a manifest that declares components to the system; compileSdk, minSdk and targetSdk each control something different.
  • The activity lifecycle exists because the system controls when your app runs — expect recreation on configuration changes and process death in the background, and keep state in a ViewModel with SavedStateHandle for the rest.
  • Jetpack Compose is the recommended UI toolkit: hoist state, pass a Modifier, and let recomposition redraw what changed; the View system remains essential for reading existing code.
  • Structure the app as UI, optional domain and data layers with a single immutable state object per screen and events flowing back as callbacks.
  • Coroutines with viewModelScope and Flow keep work off the main thread and cancel with the screen; WorkManager is only for work that must survive the app being closed.
  • Choose storage by shape — DataStore for preferences, Room for structured data — and request runtime permissions at the point of use, preferring APIs that need none.

Sources and further reading

Frequently asked questions

Should I learn Compose or XML layouts first?
Learn Compose first, because it is the recommended toolkit for new user interfaces and it is where the documentation and libraries are heading. You will still need to read XML layouts, since an enormous amount of production code uses them and interoperability is common in mixed screens. Treat the View system as something you can maintain rather than something you would choose for a new screen.
Why does my app lose state when the screen rotates?
A configuration change destroys and recreates the activity so it can reload resources for the new configuration. Anything held in an activity field is lost. Keep screen state in a ViewModel, which survives the recreation, and put the small amount that must survive the process being killed in SavedStateHandle. Blocking rotation is not a fix; the same recreation happens for locale changes, dark mode and multi-window.
What is the difference between a coroutine and WorkManager?
A coroutine runs work now, scoped to something alive — usually a ViewModel — and is cancelled when that scope ends. WorkManager schedules deferrable work that must eventually complete even if the user leaves the app or the device reboots, such as uploading a queued report. Use coroutines for anything driving the current screen and WorkManager only when guaranteed execution matters.
Do I need a dependency injection framework?
Not to start. Constructing dependencies by hand in a small app is clear and has no build cost. As the graph grows, passing a database, a network client and half a dozen repositories through every constructor becomes noise, and a framework such as Hilt generates that wiring and makes swapping fakes in tests straightforward. Adopt it when manual wiring starts hurting, not before.