Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 104 ยท Getting Started

The Four Components and How Android Runs Your App

Learn the four Android app components, how processes are created and ranked, which apps the system kills first, and the difference between cold, warm and hot starts.

An Android app is not one program with a main function. It is a bundle of components that the operating system starts, pauses and kills on its own schedule. You never write "run the app"; you declare components in the manifest, and the system creates them when something needs them: the user taps an icon, a notification is tapped, another app shares a photo to you, an alarm goes off. Once you see your app as a set of entry points that live inside a process the system can destroy, a lot of Android's rules (lifecycles, saved state, background limits) stop looking arbitrary.

This lesson names the four component types, explains how Android decides which process your code runs in, how it chooses which processes to kill when memory runs low, and what happens during a cold, warm or hot start. The Android classes cannot run on this site, so the real code is read-only and the TryIts are plain Kotlin stand-ins: one models process importance and the kill order, the other models the three kinds of start. Later lessons go deep on each piece, for example Activities, Intents and Services.

The four components

Every entry point into your app is one of four types.

Four ways in

Activity One screen the user sees
Service Work with no screen
Broadcast receiver Reacts to an event
Content provider Shares data with others

Each one is declared in the manifest and started by the system.

1 / 2
  • An Activity is a single focused thing the user can do, usually one screen. In a modern Compose app you often have just one activity that hosts all your composables, see Activities and setContent.
  • A Service runs work without a screen of its own, such as music playback. It does not mean "background thread"; read Services, Notifications and Foreground Work.
  • A BroadcastReceiver receives a short event: the battery is low, the device finished booting, the network changed. See Broadcast Receivers.
  • A ContentProvider exposes structured data to other apps (and to your own code) through URIs. See Content Providers.

All four, plus the app itself, are declared in AndroidManifest.xml (see The Manifest and Resources). Components are started with intents for activities, services and receivers, and with a ContentResolver for providers. The key rule is that components are independent. An email app can start your "share" activity without your Application object having been used for anything else, and your broadcast receiver can run when no activity exists at all.

XML
<!-- read-only example: the four component types in a manifest -->
<application android:name=".MyApp">
    <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>

    <service android:name=".SyncService" android:exported="false" />

    <receiver android:name=".BootReceiver" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

    <provider
        android:name=".NotesProvider"
        android:authorities="com.example.notes.provider"
        android:exported="false" />
</application>

The Application subclass (.MyApp) is not a component, but it is the object created first in every process and lives as long as the process. It is the right place for one-time setup such as dependency-injection containers and logging.

Processes and threads

When the first component of your app is needed, the system starts a Linux process for your app, creates a main thread (also called the UI thread) in it, and instantiates your Application class, then the component. By default all components of an app run in the same process with the same main thread. That is why a slow call in onCreate() of an activity or onReceive() of a receiver freezes the UI: they share one thread.

A few consequences are worth memorizing:

  1. Each app has its own process (and its own Linux user ID), so apps cannot read each other's memory or files. Sharing happens only through intents, providers and other controlled channels.
  2. A process can be killed at any time when the system needs memory. Your variables, singletons and in-memory caches vanish with it. This is the reason saved state and persistent storage exist.
  3. You can ask for extra processes with android:process on a component, but it is rarely a good idea: static fields are no longer shared and each process pays its own memory and startup cost.

Process importance and the kill order

Android keeps processes alive for as long as it can, because starting one is slow, and kills them only when memory runs short. To pick victims it ranks every process by importance, based on the most important component it currently hosts. From most to least important:

Rank Process state Typical example
1 Foreground The activity the user is looking at, a running foreground service, a receiver in onReceive()
2 Visible An activity that is visible but not in focus (behind a dialog or split screen)
3 Service A started service that is not a foreground service, such as a sync job
4 Cached An activity the user left (stopped), no active components

The cached processes sit in a list ordered by how recently they were used, the LRU list (least recently used). When memory is low, the system's low-memory killer daemon (lmkd) kills from the bottom: cached processes first, the least recently used one before newer ones. Foreground processes are killed only when nothing else is left, which on a healthy phone almost never happens.

Two things follow for you as a developer:

  • When the user presses Home, your activity is stopped, and your process becomes cached. It may live for hours, or die in seconds. Never rely on it staying alive.
  • A process hosting a bound service or provider used by a more important process is ranked as high as the client. A music app's playback service in the foreground keeps the whole process safe.

The first stand-in ranks a few pretend processes, fills memory and kills them in the order the system would.

Kotlin Process importance and LRU killing (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that the 3-hour-old game dies before the mail app that was used five minutes ago, even though it uses more memory: rank first, recency second. Memory size is not the deciding factor.

Cold, warm and hot starts

How long an app takes to appear depends on how much of it already exists. The system distinguishes three starts.

flowchart LR
    T["User taps the icon"] --> Q{"Is the process alive?"}
    Q -->|"No"| C["Cold start<br/>create process, Application,<br/>activity, first frame"]
    Q -->|"Yes, activity gone"| W["Warm start<br/>recreate the activity,<br/>restore saved state"]
    Q -->|"Yes, activity in memory"| H["Hot start<br/>onRestart, onStart, onResume"]

The more already exists, the less work the system has to do.

  • Cold start: the process does not exist. The system must create it, start the runtime, create Application and run Application.onCreate(), then create the launch activity, inflate or compose the first screen, and draw the first frame. This is the slowest and the one you optimize.
  • Warm start: the process still exists but the activity was destroyed (for example after a back press, or a configuration change). The system skips process creation and Application.onCreate(), but runs the activity's onCreate() again, usually with a savedInstanceState bundle.
  • Hot start: the process and the activity are both still in memory. The activity just goes onRestart, onStart, onResume. This is the fastest start and the one users get most often.

The metric the Play Console reports (see Performance and Profiling) is the time to initial display: from the tap to the first frame. Google's "excessive start-up time" thresholds are about 5 seconds for a cold start and 2 seconds for warm and hot. To keep cold starts fast:

  • Do almost nothing in Application.onCreate(). Create objects lazily, or move work off the main thread.
  • Keep the first screen light. Show something immediately and load the rest afterward.
  • Use the SplashScreen API (androidx.core:core-splashscreen) for the launch screen instead of a custom "splash activity", which only adds another activity creation to the cold start.
  • Ship a Baseline Profile, which precompiles the startup code path so it does not run in slow interpreted mode on first launch.

Initialization with App Startup

Libraries used to initialize themselves by hiding a ContentProvider in their manifest, because providers are created before Application.onCreate(). Ten such libraries meant ten providers slowing down every cold start. The App Startup library (androidx.startup) replaces them with a single provider and an ordered list of Initializer classes.

Kotlin
// read-only example: an initializer with a dependency
class LoggerInitializer : Initializer<Logger> {
    override fun create(context: Context): Logger = Logger.init(context)
    override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}

class AnalyticsInitializer : Initializer<Analytics> {
    override fun create(context: Context): Analytics = Analytics.start(context)
    override fun dependencies() = listOf(LoggerInitializer::class.java) // runs after the logger
}

You can also turn automatic initialization off for an initializer and call AppInitializer.getInstance(context).initializeComponent(...) the first time the feature is used, so the cost leaves the startup path completely. The second stand-in simulates the three starts and shows which callbacks run in each.

Kotlin Cold, warm and hot start (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The numbers are invented for the model; real timings depend on the device. The shape is real: each step down the list from cold to hot removes whole stages of work.

Common mistakes

  • Storing important data only in a singleton or a static variable. It disappears when the process is killed. Persist data, and restore UI state from saved state.
  • Assuming your process is alive after a long time in the background. After a few minutes it may be gone, and the next tap is a cold start.
  • Heavy work in Application.onCreate() or in a hidden provider. Everything there is added to every cold start.
  • Doing slow work in onReceive(). The receiver runs on the main thread and the system may kill the process once it returns. Read Broadcast Receivers.
  • Putting components in separate processes without a reason. It breaks shared state and costs memory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is NOT one of the four Android app components?

    The four components are Activity, Service, BroadcastReceiver and ContentProvider. The Application class is created once per process but is not a component.
  2. 2. The user presses Home and leaves your app for hours. What is the most accurate description of your process?

    A process with no active components is cached. The system keeps it only while memory allows and kills cached processes in LRU order.
  3. 3. The process is alive but the activity was destroyed with Back. The user taps the icon. What kind of start is this?

    The process exists, so there is no process creation or Application.onCreate(), but the activity must be created again. That is a warm start.
  4. 4. Why does the App Startup library exist?

    Each library that initializes itself through its own provider adds cost to cold start. App Startup runs one provider and a dependency-ordered list of Initializers.
  5. 5. Which process is the system most likely to kill first when memory is low?

    Cached processes rank lowest and the least recently used one goes first.

Summary

  • An app is a set of components (activity, service, broadcast receiver, content provider) declared in the manifest and started by the system.
  • All components of an app share one process and one main thread by default; a slow callback anywhere freezes the UI.
  • Processes are ranked foreground, visible, service and cached; cached ones are killed first, least recently used first.
  • Your process can disappear at any moment, so persist data and restore state instead of trusting memory.
  • A cold start creates the process, a warm start recreates the activity, a hot start only brings it back.
  • Keep Application.onCreate() small, use the SplashScreen API, App Startup and a Baseline Profile.
  • The Android code is read-only; the TryIts model ranking and the three starts.

Next: Context in Android