Skip to content
Commitwise
Menu
Android Development

App components and Intents: activities, services, receivers and providers

The four Android app components and how the system starts them. Explicit and implicit intents, package visibility, launch modes and onNewIntent, the Activity Result API, started and bound services with foreground service rules, broadcast receivers and their limits, and sharing files safely with ContentProvider and FileProvider.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A “Share” button that does nothing on new phones. A chat notification that opens the wrong conversation. A music player that stops after a minute in the background, and a photo upload that crashes with FileUriExposedException. None of these are Compose bugs: they’re about how Android itself starts and connects the pieces of an app.

An Android app isn’t one program with a main function. It’s a set of components the system can start separately, each declared in the manifest, and they talk through intents. This is the classic Android interview topic (“name the four components”, “what’s the difference between a started and a bound service?”) and it’s behind many real production bugs.

New to some of these? Open what you need, or skip ahead.

Basics:What is the manifest?

AndroidManifest.xml is the app’s description for the system: its package name, the permissions it needs, and every component it has. The system reads it at install time, so it knows which screens exist and which links or events the app can handle before the app ever runs.

Basics:What is an Intent?

An Intent is a message that asks the system to do something: “open this screen”, “share this text”, “start this background service”. It can name the exact class to start, or just describe an action (“view this web page”) and let the system find an app that handles it. Intents can carry small pieces of data called extras.

Part Not started

Intents and activities

Every Android app is built from up to four kinds of components:

ComponentWhat it isExample
Activitya screen the user interacts withthe chat screen
Servicework without a screenplaying music, a long upload
BroadcastReceiverreacts to system or app events“the phone finished booting”
ContentProvidershares data with other apps through content:// URIsthe contacts database, your app’s files

Modern apps often have a single Activity with Compose screens inside it, but the other three still matter whenever you work outside your own screens.

You start components with an Intent:

  • An explicit intent names the class: Intent(context, SettingsActivity::class.java). Use it inside your own app.
  • An implicit intent describes what you want: “view this URL”, “send this text”. The system looks at the intent filters that apps declare in their manifests, and either opens the matching app or shows a chooser.

If no installed app can handle an implicit intent, startActivity throws ActivityNotFoundException, and an uncaught exception crashes your app. That happens more often than you’d think: on tablets without a dialer, in work profiles, on devices without an email app.

Components are entry points the system instantiates by itself, in your process, possibly after process death, which is why they need no-arg constructors and must restore their state from the intent and saved state rather than from fields set by a caller. Implicit intents are resolved against <intent-filter>s (action, category, data); exported must be explicit on any component with a filter since Android 12, and the exported surface is an attack surface (see Which components should be exported?). Package visibility (Android 11, API 30) filters PackageManager queries, including resolveActivity and queryIntentActivities, unless you declare <queries>; startActivity itself isn’t filtered, so the robust pattern is “try and catch ActivityNotFoundException”, with <queries> only when you must show or hide UI in advance. Launch modes and flags shape the task and back stack: singleTop (or FLAG_ACTIVITY_SINGLE_TOP) routes a repeat launch to onNewIntent on the existing top instance, singleTask/singleInstance reuse one instance per task, and FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK builds a fresh task from a notification. startActivityForResult is deprecated in favor of the Activity Result API (registerForActivityResult, registered before the component reaches STARTED, with typed contracts such as PickVisualMedia and RequestPermission), which survives configuration changes and process death.

// Explicit: a screen in this app
startActivity(Intent(this, SettingsActivity::class.java).putExtra("section", "privacy"))

// Implicit: any app that can share text
val share = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_TEXT, "Try this recipe: https://recipes.example.com/r/42")
}
startActivity(Intent.createChooser(share, "Share recipe"))

// A result from another screen: the photo picker (no permission needed)
val pickPhoto = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
    if (uri != null) viewModel.onPhotoPicked(uri)
}
// later, in a click handler:
pickPhoto.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))

Predict the output

ChatActivity is declared with launchMode='singleTop' and is open on chat 7. A notification for chat 9 starts ChatActivity with chatId = 9. Which chat does the screen show?

class ChatActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val chatId = intent.getLongExtra("chatId", -1)
        setContent { ChatScreen(chatId) }
    }
}

A Share button that does nothing

Spot the bugEmail support works on the emulator, not on users' phones

Tap the line with the bug.

fun emailSupport() {
    val intent = Intent(Intent.ACTION_SENDTO).apply {
        data = Uri.parse("mailto:support@example.com")
        putExtra(Intent.EXTRA_SUBJECT, "Help with my order")
    }
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }
}

Tasks, notifications and back

A notification that opens a deep screen should give the user a sensible Back: build the back stack with TaskStackBuilder (or a Navigation deep link with createPendingIntent(), which does it for you), or start a fresh task with FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK. The PendingIntentPendingIntentA token that lets the system or another app perform an intent later on your app's behalf, for example when a notification is tapped.Open in glossary → needs FLAG_IMMUTABLE (required to pick one since Android 12) and a unique request code or data URI per conversation, because PendingIntents that differ only in extras are considered equal and the second one reuses the first one’s extras (unless you pass FLAG_UPDATE_CURRENT, which then changes the first notification’s target too).

Deep diveWhy components must not depend on the caller's objectsInterview favorite

Interviewers like asking why you can’t just pass an object to a new Activity’s constructor. The system, not your code, creates components, using reflection and a no-arg constructor. It may create them in a fresh process after process deathProcess deathAndroid killing a background app to free memory, then recreating the last screen from saved state when the user returns.Open in glossary →: the user leaves the app, the system kills the process, and later recreates the top Activity from its saved Intent and Bundle.

That’s why everything a component needs must travel in the intent (small, parcelable data like ids) or be loaded from storage, and why passing a 5 MB bitmap in extras fails with TransactionTooLargeException: intents cross process boundaries through Binder, whose transaction buffer is about 1 MB shared by the whole process. Pass an id or a content:// URI instead.

  • Four components, all system-instantiated entry points; restore state from the intent and saved state, never from caller-set fields.
  • Implicit intents match intent filters; package visibility (API 30) filters resolveActivity without <queries>, so start and catch ActivityNotFoundException.
  • singleTop → onNewIntent + setIntent; build notification back stacks with TaskStackBuilder; unique PendingIntents per target, FLAG_IMMUTABLE.
  • Activity Result API instead of startActivityForResult, registered before STARTED. Large extras → TransactionTooLargeException (Binder ≈ 1 MB).

Check this part

  1. What happens when startActivity gets an implicit intent that no installed app handles?

  2. Which intent should you use to open a screen inside your own app?

  3. Why does intent.resolveActivity(packageManager) return null on Android 11+ even though a matching app is installed?

  4. A singleTop Activity at the top of the task is started again. Which callback receives the new intent?

Four components: Activity, Service, BroadcastReceiver, ContentProvider, all declared in the manifest. Explicit intents name a class; implicit intents describe an action and are matched against intent filters. On Android 11+ resolveActivity hides other apps unless declared in queries, so just start and catch ActivityNotFoundException. singleTop sends repeat launches to onNewIntent. Use the Activity Result API.

Part Not started

Services: work without a screen

A Service is a component for work that has no screen. Two facts surprise almost everyone:

  • A Service is not a background thread. Its callbacks run on the main thread, like an Activity’s. A network call in onStartCommand freezes the app just as much as one in a click handler. You still need coroutines or another thread inside it.
  • Android limits background services hard, to save battery. An app that isn’t visible can’t keep an ordinary service running: the system stops it within about a minute.

So when do you use a service today?

  • Foreground service: work the user knows about and expects to continue right now, shown with an ongoing notification: playing music, navigation, a call, a workout being tracked.
  • Bound service: another component (or another app) connects to it and calls its methods while connected, like a media player your UI controls.

For work that only has to happen eventually, like syncing or uploading logs, use WorkManager instead (see WorkManager and background work). It survives restarts and respects battery rules.

Started services (startService/startForegroundService → onStartCommand) run until stopSelf/stopService; the return value (START_NOT_STICKY, START_STICKY, START_REDELIVER_INTENT) tells the system whether to recreate it after killing it. Bound services (bindService → onBind returns an IBinder) live while at least one client is bound, unless also started; in-process clients cast the binder to a local class, cross-process ones use Messenger or AIDL. Services always run on the main thread (IntentService is deprecated since API 30); use LifecycleService + lifecycleScope or your own scope cancelled in onDestroy. Platform limits stack up: Android 8 background execution limits stop background services and throw IllegalStateException on startService from the background; startForegroundService requires startForeground() within a few seconds; Android 12 forbids starting foreground services from the background (ForegroundServiceStartNotAllowedException) except for listed cases such as high-priority FCM messages and exact alarms; Android 13 requires POST_NOTIFICATIONS for the notification to show (the service still runs); Android 14 requires a foregroundServiceType in the manifest plus a matching FOREGROUND_SERVICE_* permission, and Google Play reviews the declared types. The choice between WorkManager and a foreground service is a frequent interview question: WorkManager or a foreground service?

class WorkoutService : LifecycleService() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        ServiceCompat.startForeground(                      // within a few seconds of starting
            this, NOTIFICATION_ID, buildOngoingNotification(),
            ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION,
        )
        lifecycleScope.launch {                             // the work runs off the main thread
            locationClient.updates().collect { tracker.add(it) }
        }
        return START_NOT_STICKY                             // don't restart silently after being killed
    }
}

// From a visible screen (the user tapped Start):
ContextCompat.startForegroundService(context, Intent(context, WorkoutService::class.java))
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />

<service
    android:name=".WorkoutService"
    android:exported="false"
    android:foregroundServiceType="location" />

A service that freezes the app

Spot the bugExport button, then 'App isn't responding'

Tap the line with the bug.

class ExportService : Service() {
    override fun onBind(intent: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val rows = database.allOrders()          // 50,000 rows
        val file = csvWriter.write(rows)
        uploader.upload(file)                    // a slow network call
        stopSelf()
        return START_NOT_STICKY
    }
}

A bound service for a player

class PlayerService : Service() {
    inner class LocalBinder : Binder() { val service get() = this@PlayerService }
    private val binder = LocalBinder()
    val state = MutableStateFlow(PlayerState.Idle)

    override fun onBind(intent: Intent): IBinder = binder
    fun play(trackId: String) { /* … */ }
}

class PlayerActivity : ComponentActivity() {
    private var player: PlayerService? = null
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, binder: IBinder) {
            player = (binder as PlayerService.LocalBinder).service
        }
        override fun onServiceDisconnected(name: ComponentName) { player = null }   // only if the process crashed
    }

    override fun onStart() {
        super.onStart()
        bindService(Intent(this, PlayerService::class.java), connection, BIND_AUTO_CREATE)
    }
    override fun onStop() {
        unbindService(connection)
        player = null
        super.onStop()
    }
}

For real media playback, use Jetpack Media3’s MediaSessionService, which handles the foreground notification, lock-screen and Bluetooth controls, and Android Auto; your UI connects through a MediaController instead of a raw binder.

Deep diveWhy START_STICKY is rarely what you wantInterview favorite

START_STICKY asks the system to recreate the service after it kills the process, calling onStartCommand with a null intent. The work the intent described is lost, so the service wakes up not knowing what it was doing. Code that assumes a non-null intent crashes.

START_REDELIVER_INTENT redelivers the last intent, which fits “finish this one job”. But for anything that must survive process death reliably, persist the job and let WorkManager run it: it stores work in its own database and resumes it after reboots, which no service return value does.

  • Services run on the main thread; started (until stopped, START_* restart semantics) vs bound (while clients are bound; Binder, Messenger, AIDL).
  • Android 8 background limits; startForeground within a few seconds; Android 12 no FGS start from background; Android 14 foregroundServiceType + FOREGROUND_SERVICE_* permission.
  • Deferrable or must-survive-reboot work → WorkManager; user-visible ongoing work → foreground service; media → Media3 MediaSessionService.

Check this part

  1. On which thread does a Service's onStartCommand run?

  2. Which fits a running workout the user is tracking right now?

  3. What does Android 14 require for a foreground service?

  4. A bound service that was never started. When does it stop?

A Service is work without a screen, but it runs on the main thread. Started services run until stopped; bound services live while clients are bound. Since Android 8 background services are limited, since Android 12 foreground services can't start from the background, and since Android 14 they need a type. Prefer WorkManager for deferrable work.

Part Not started

Broadcast receivers and content providers

A BroadcastReceiver reacts to events: the phone finished booting, the language changed, an alarm went off. Its onReceive runs on the main thread and must finish within a few seconds; for anything longer, hand the work to WorkManager. Receivers come in two kinds:

  • Declared in the manifest: the system can start your app to deliver the event. Since Android 8, only a short list of system broadcasts (like BOOT_COMPLETED and LOCALE_CHANGED) still reach manifest receivers.
  • Registered in code while a screen or service is alive, and unregistered when it stops.

A ContentProvider exposes data to other apps through content:// URIs, read with a ContentResolver. You use other apps’ providers often (contacts, the media store) but rarely write one, with one big exception: sharing a file. A file path like file:///data/user/0/com.app/files/photo.jpg is private to your app, so you give other apps a content:// URI from FileProvider, together with temporary permission to read it.

Receivers: onReceive runs on the main thread with an ANR limit of about 10 seconds for foreground broadcasts; goAsync() returns a PendingResult to finish off the main thread within the same limit, and the process may be killed right after it returns, so anything longer goes to WorkManager. Android 8 stopped delivering most implicit broadcasts to manifest receivers (explicit ones and an exemption list still work); runtime receivers must pass RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED when targeting Android 14 (ContextCompat.registerReceiver handles older versions), and receivers that react to other apps should demand a permission. For in-app events, use a Flow instead of broadcasts (LocalBroadcastManager is deprecated). Providers: a ContentProvider is initialized in Application startup, before Application.onCreate, which is why libraries used them for auto-initialization (Jetpack App Startup merges them into one) and why heavy provider onCreates slow cold start. Sharing: file:// URIs to other apps throw FileUriExposedException (targeting Android 7+); use FileProvider.getUriForFile with FLAG_GRANT_READ_URI_PERMISSION (and ClipData for ACTION_SEND) so the grant lasts only as long as the receiving activity, keep the provider unexported, and keep file_paths.xml narrow. Querying providers: contentResolver.query(...).use { }, ContentObserver for changes, and the photo picker or MediaStore instead of broad storage permissions.

fun sharePhoto(photo: File) {   // a file in cacheDir/shared/
    val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", photo)
    val send = Intent(Intent.ACTION_SEND).apply {
        type = "image/jpeg"
        putExtra(Intent.EXTRA_STREAM, uri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)   // the receiving app may read this one file, for now
    }
    context.startActivity(Intent.createChooser(send, "Share photo"))
}
<!-- AndroidManifest.xml -->
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

<!-- res/xml/file_paths.xml: only this folder can be shared -->
<paths>
    <cache-path name="shared_images" path="shared/" />
</paths>

Predict the output

An app targeting Android 14 registers a receiver for its own custom broadcast with registerReceiver(receiver, IntentFilter('com.example.SYNC_DONE')), without any flag. What happens?

override fun onStart() {
    super.onStart()
    registerReceiver(syncReceiver, IntentFilter("com.example.SYNC_DONE"))
}

A crash when sharing a receipt

Spot the bugShare receipt crashes the app

Tap the line with the bug.

fun shareReceipt(pdf: File) {
    val send = Intent(Intent.ACTION_SEND).apply {
        type = "application/pdf"
        putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pdf))
    }
    startActivity(Intent.createChooser(send, "Share receipt"))
}

Rescheduling after a reboot

Alarms set with AlarmManager are cleared on reboot, and this is one of the few cases where a manifest receiver still makes sense: BOOT_COMPLETED (with RECEIVE_BOOT_COMPLETED) to reschedule exact reminders. Keep onReceive tiny and enqueue the real work. WorkManager already reschedules its own work after reboots, so if your reminders are WorkManager jobs you don’t need the receiver at all.

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_BOOT_COMPLETED) return     // filter actions, don't trust the sender
        WorkManager.getInstance(context)
            .enqueue(OneTimeWorkRequestBuilder<RescheduleRemindersWorker>().build())
    }
}
Deep diveWhy ContentProviders run before Application.onCreateInterview favorite

When a process starts, the system creates the Application object, calls attachBaseContext, then installs every ContentProvider declared in the manifest (calling each provider’s onCreate), and only then calls Application.onCreate. Providers come first because another app might be waiting to query one: that request may be the very reason the process started.

Libraries use this to initialize themselves with no code from you (Firebase still does, and WorkManager did before App Startup), each with its own empty provider, which cost a few milliseconds of cold start apiece. Jetpack App Startup replaces them with one shared provider and explicit Initializer dependencies, and lets you disable automatic initialization of a library and run it lazily. When you profile slow startup, check for providers in the merged manifest.

  • Receivers: main thread, ~10 s, goAsync for short async work, WorkManager for more. Android 8 limits implicit broadcasts to manifest receivers; Android 14 needs RECEIVER_EXPORTED/NOT_EXPORTED. In-app events → Flow.
  • Providers initialize before Application.onCreate (App Startup merges library initializers); query with use {}, observe with ContentObserver.
  • Share files via FileProvider + FLAG_GRANT_READ_URI_PERMISSION, unexported provider, narrow paths; file:// → FileUriExposedException.

Check this part

  1. How do you give another app access to a file in your app's storage?

  2. What should a BroadcastReceiver do with a long task in onReceive?

  3. What changed for runtime-registered receivers in apps targeting Android 14?

  4. When does a ContentProvider's onCreate run?

BroadcastReceivers react to events in onReceive, on the main thread and for a few seconds only; most implicit broadcasts can't reach manifest receivers since Android 8, and runtime receivers need an exported flag since Android 14. ContentProviders share data through content:// URIs; share files with FileProvider and temporary URI permissions, never file:// paths.

Key takeaways

  • An Android app is made of Activities, Services, BroadcastReceivers and ContentProviders, all declared in the manifest and started by the system.
  • Explicit intents open your own screens; implicit intents ask other apps. Always catch ActivityNotFoundException.
  • A singleTop Activity gets repeat launches in onNewIntent, not onCreate.
  • Services run on the main thread. Use foreground services for visible, ongoing work and WorkManager for everything that can wait.
  • Share files with FileProvider and a temporary read permission, never with file:// paths.
  • Components are system-created entry points; they rebuild from intents and saved state, and large extras hit the ~1 MB Binder limit.
  • Package visibility, launch modes, PendingIntent identity and the Activity Result API cause most intent bugs.
  • Know the service timeline: Android 8 limits, Android 12 no background FGS starts, Android 14 types and permissions; prefer WorkManager or Media3.
  • Receivers are short and increasingly restricted; providers initialize before Application.onCreate and are how apps share files safely.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.