Intents and activities
Every Android app is built from up to four kinds of components:
| Component | What it is | Example |
|---|---|---|
| Activity | a screen the user interacts with | the chat screen |
| Service | work without a screen | playing music, a long upload |
| BroadcastReceiver | reacts to system or app events | “the phone finished booting” |
| ContentProvider | shares data with other apps through content:// URIs | the 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) }
}
}Because ChatActivity is already at the top of the task, singleTop doesn't create a new instance: the system calls onNewIntent(intent) on the existing one. This code reads the chat id only in onCreate, so the screen stays on chat 7. Override onNewIntent, call setIntent(intent) so later reads see it, and load the new chat.
A Share button that does nothing
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)
}
}Hint: The app targets Android 14. Since Android 11, what does the PackageManager tell you about other apps?
Since Android 11, apps can’t see most other installed apps through PackageManager. Without a <queries> entry in the manifest, resolveActivity returns null even when Gmail is installed, so tapping the button silently does nothing. It worked while the app targeted an older version, which is why old tutorials still show this pattern.
startActivity itself isn’t affected. Just start the intent and handle the case where no app exists:
fun emailSupport() {
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:support@example.com"))
.putExtra(Intent.EXTRA_SUBJECT, "Help with my order")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
snackbar("No email app found. Write to support@example.com")
}
}Add <queries> only when you need to know in advance, for example to hide the button when no app can handle it.
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
resolveActivitywithout<queries>, so start and catchActivityNotFoundException. singleTop→onNewIntent+setIntent; build notification back stacks withTaskStackBuilder; unique PendingIntents per target,FLAG_IMMUTABLE.- Activity Result API instead of
startActivityForResult, registered before STARTED. Large extras →TransactionTooLargeException(Binder ≈ 1 MB).
Check this part
What happens when startActivity gets an implicit intent that no installed app handles?
Which intent should you use to open a screen inside your own app?
Why does intent.resolveActivity(packageManager) return null on Android 11+ even though a matching app is installed?
A singleTop Activity at the top of the task is started again. Which callback receives the new intent?