Intents and intent filters
Why it matters
- Every screen transition, share action, deep link, and notification tap goes through an Intent. A wrong filter or a wrong
android:exportedvalue quietly breaks navigation in production. - Interviewers ask about explicit vs implicit resolution, what happens when several apps match, and what changed in recent Android versions.
- Package visibility (Android 11) and explicit
android:exported(Android 12) are common surprises when you raisetargetSdk. PendingIntentmutability flags and the Activity Result APIs replaced older patterns. Missing the flag crashes on Android 12+ when you target API 31.- Deep links and App Links depend on correct intent filters. A mistake in
android:pathPatternmeans your marketing links open the wrong screen or nothing at all.
The simple explanation
- An Intent is a bus ticket: it says where you want to go and what you carry (extras).
- An explicit Intent names the exact stop (a component class). No ambiguity.
- An implicit Intent says "take me to any restaurant". The system checks the registered filters to find matches.
- An intent filter is the sign on a restaurant door: it lists what kind of requests it accepts (action, data, category).
android:exported="false"means the restaurant is behind a gate: only your own app can walk in.- Package visibility (Android 11+) means the city hides other restaurants from your directory lookups unless you declare which ones you need to find.
An Intent is a message object. It carries an action (a string such as Intent.ACTION_VIEW), optional data (a Uri) and MIME type, extras (a Bundle), categories, and optionally a component (an explicit target).
Explicit vs implicit. An explicit intent names its target with Intent(context, DetailActivity::class.java), setClass() or setComponent(). The system starts that exact component and skips filter matching. An implicit intent has no component; the system compares it with the intent filters of installed apps.
Intent filters live inside <activity>, <service>, or <receiver> tags. Each filter lists action, category, and data elements. An intent must pass all three tests:
- Action: the intent's action must be one of the filter's actions.
- Category: every category in the intent must be listed in the filter.
startActivityaddsCATEGORY_DEFAULTto implicit intents, so an activity filter needsDEFAULTto receive them. - Data: the intent's URI and MIME type must match the filter's
<data>elements.
Key flags and attributes:
| Item | What it controls | Pitfall |
|---|---|---|
android:exported | Whether other apps can start the component | Required with intent filters when targeting API 31+; omitting it fails the build |
android:autoVerify | Asks the system to verify App Links (HTTPS links) | Needs /.well-known/assetlinks.json on your domain |
<queries> element | Which other apps your app can see through PackageManager (target API 30+) | Without it, queryIntentActivities leaves those apps out |
PendingIntent mutability | FLAG_IMMUTABLE vs FLAG_MUTABLE | Required when targeting API 31+; omitting it throws IllegalArgumentException |
When several activities match an implicit startActivity, the user picks one in a disambiguation dialog (and can make it the default), unless a verified App Link or an existing default decides. Intent.createChooser always shows the system share sheet. If nothing matches, startActivity throws ActivityNotFoundException.
Package visibility affects lookups, not launches. startActivity with an implicit intent and the system chooser work without <queries>. You need <queries> when your code asks PackageManager about other apps, for example queryIntentActivities, resolveActivity or getPackageInfo.
Activity Result API (registerForActivityResult) replaced startActivityForResult / onActivityResult, which are deprecated. You get a type-safe contract and a callback instead of request codes, and the registry restores pending requests after the Activity is recreated, as long as you register again on every creation.
Notes
- An explicit intent sets a component. An implicit intent leaves it null and relies on filter matching. If you set both a component and an action, the component decides where it goes; the action is still delivered as data.
- When targeting API 31+, every
<activity>,<service>, and<receiver>with an intent filter must declareandroid:exported. The build fails if it is missing. - Package visibility applies when you target API 30+.
queryIntentActivities,resolveActivityandgetPackageInfoonly see apps you declared in<queries>(plus a few always-visible ones). Prefer a narrow<intent>query overQUERY_ALL_PACKAGES, which Google Play restricts. - When targeting API 31+, every
PendingIntentneedsFLAG_IMMUTABLEorFLAG_MUTABLE. UseFLAG_IMMUTABLEunless something like an inline reply or a bubble must fill in the intent. - When targeting API 34+, implicit intents are only delivered to exported components, and a mutable
PendingIntentmust not wrap an implicit intent. - When targeting API 33+, an intent sent by another app to your exported component is only delivered if it matches one of that component's filters.
- Data from another app's intent (extras, the URI) is untrusted input. Validate it before you use it.
<data>attributes:scheme,host,port,path,pathPrefix,pathPattern(andpathSuffix,pathAdvancedPatternon API 31+).pathPatternis a simple pattern where only.and*are special, not a full regex.android:autoVerify="true"on anhttpsfilter asks the system to verify your domain throughassetlinks.json. Verified links open your app directly. On Android 12+, unverified web links open in the browser by default.FLAG_ACTIVITY_CLEAR_TOPtogether withFLAG_ACTIVITY_SINGLE_TOPbrings an existing instance to the top of its task and delivers the new intent toonNewIntent. WithCLEAR_TOPalone, astandardactivity is finished and recreated.
Code example
An Activity that uses an explicit intent with the Activity Result API, and an implicit share intent through the system chooser.
class MainActivity : AppCompatActivity() {
// Register as a field: it must happen before the Activity reaches STARTED.
private val pickItem = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
val id = result.data?.getStringExtra(PickItemActivity.EXTRA_ITEM_ID)
Log.d("Main", "picked $id")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.btnPick).setOnClickListener {
// Explicit: names the class, so no filter matching happens.
pickItem.launch(Intent(this, PickItemActivity::class.java))
}
findViewById<Button>(R.id.btnShare).setOnClickListener {
// Implicit: any app with a matching ACTION_SEND filter can handle it.
val send = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, "https://example.com/items/42")
}
// The system share sheet. No <queries> entry is needed for this.
startActivity(Intent.createChooser(send, null))
}
}
}The matching manifest entries:
<!-- Inside <application> -->
<activity android:name=".ItemActivity" android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" />
<data android:host="example.com" />
<data android:pathPrefix="/items/" />
</intent-filter>
</activity>
<!-- Only reachable from this app, through explicit intents -->
<activity android:name=".PickItemActivity" android:exported="false" />
<!-- Inside <manifest>: only needed if code asks PackageManager about these apps -->
<queries>
<intent>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="text/plain" />
</intent>
</queries>registerForActivityResultis safe to call as a field initializer or inonCreate. Calling it once the Activity is alreadySTARTEDthrowsIllegalStateException.PickItemActivityreturns its answer withsetResult(RESULT_OK, Intent().putExtra(EXTRA_ITEM_ID, id))and thenfinish().ItemActivityreads the link inonCreatefromintent.data, and inonNewIntentif it can be reused.
Run the idea in plain Kotlin
A small model of the three matching tests, including the DEFAULT category that startActivity adds.
data class Filter(
val actions: Set<String>,
val categories: Set<String>,
val schemes: Set<String>,
)
data class Msg(
val action: String?,
val categories: Set<String> = emptySet(),
val scheme: String? = null,
val component: String? = null, // non-null = explicit
)
const val DEFAULT = "DEFAULT"
fun matches(msg: Msg, filter: Filter): Boolean {
// Action test: the intent's action must be one of the filter's actions.
val actionOk = if (msg.action == null) filter.actions.isNotEmpty() else msg.action in filter.actions
// Category test: every category in the intent must be in the filter.
val categoryOk = filter.categories.containsAll(msg.categories)
// Data test (scheme only, to keep it short).
val dataOk = if (msg.scheme == null) filter.schemes.isEmpty() else msg.scheme in filter.schemes
return actionOk && categoryOk && dataOk
}
// startActivity() adds CATEGORY_DEFAULT to every implicit intent.
fun canStart(msg: Msg, filter: Filter): Boolean =
if (msg.component != null) true
else matches(msg.copy(categories = msg.categories + DEFAULT), filter)
fun main() {
val withDefault = Filter(setOf("VIEW"), setOf(DEFAULT, "BROWSABLE"), setOf("https"))
val noDefault = Filter(setOf("VIEW"), setOf("BROWSABLE"), setOf("https"))
val link = Msg(action = "VIEW", scheme = "https")
println("Link -> filter with DEFAULT: " + canStart(link, withDefault))
println("Link -> filter without DEFAULT: " + canStart(link, noDefault))
println("EDIT action -> filter with DEFAULT: " + canStart(link.copy(action = "EDIT"), withDefault))
println("Explicit intent ignores filters: " + canStart(Msg(action = null, component = "DetailActivity"), noDefault))
}Expected output: true, false (the filter is missing DEFAULT), false (wrong action), true (explicit intents skip matching).
In production
- After raising targetSdk to 30, users saw an empty list in the app's own "Share to" bottom sheet.
- Logs showed no exception;
queryIntentActivitiessimply returned an empty list. - The app built its picker from
queryIntentActivitiesforACTION_SENDwith typetext/plain, but had no<queries>declaration, so other apps were invisible to it.
- Added a
<queries>block with an<intent>child matchingACTION_SENDandtext/plain. - Verified on an Android 11+ device that the picker lists other apps again.
- Turned on the lint check
QueryPermissionsNeededas an error, and considered replacing the custom picker withIntent.createChooser, which needs no<queries>at all.
- After raising targetSdk to 31, the app crashed as soon as it tried to post a notification.
- The stack trace pointed at
PendingIntent.getActivity, withIllegalArgumentException: targeting S+ requiresFLAG_IMMUTABLEorFLAG_MUTABLE. - The
PendingIntentwas created withPendingIntent.FLAG_UPDATE_CURRENTonly.
- Added
PendingIntent.FLAG_IMMUTABLEto everygetActivity,getBroadcastandgetServicecall (combined withFLAG_UPDATE_CURRENTwhere needed). - For the one inline-reply action that the system must fill in, used
FLAG_MUTABLEwith an explicit intent and a comment explaining why. - Searched the dependency tree for old library versions that created PendingIntents without a flag, and updated them.
Common mistakes
- Omitting android:exported on a filtered component. When targeting API 31+ the build fails with a manifest-merger error. Set
truefor launcher and deep-link activities,falseotherwise. - Registering for an Activity result too late.
registerForActivityResultmust be called before the Activity (or Fragment) isSTARTED, for example as a field or inonCreate. Calling it later, such as inside a click listener, throwsIllegalStateException. - Forgetting the queries element when you query other apps. When targeting API 30+,
queryIntentActivities,resolveActivityandgetPackageInfoleave out undeclared apps. Add the matching<intent>or<package>child inside<queries>. - Checking resolveActivity before startActivity. Without
<queries>it returns null even when an app could handle the intent, so you hide a working feature. CallstartActivityand catchActivityNotFoundExceptioninstead. - Creating a PendingIntent without a mutability flag. When targeting API 31+ this throws
IllegalArgumentException. UseFLAG_IMMUTABLEunless the system or another app must fill in the intent. - Trusting extras in an exported Activity. Any app can start it with any extras. Validate input, and never forward an incoming
Intentstraight tostartActivity(intent redirection).
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between an explicit and an implicit Intent?”
“What changed with android:exported and package visibility?”
“Explain the Activity Result API and why it replaced onActivityResult.”
“How do you open an existing screen from a notification without creating duplicates?”
Quiz
What happens if you set both a component and an action on an Intent?
Your app targets API 31. An Activity with an intent filter has no android:exported attribute. What happens?
Your app targets API 30. Which call needs a matching queries element to see other apps?
Which flag should a notification PendingIntent use when nothing will modify its intent?
0 of 4 answered
Mini task
Exercise: add a deep-link intent filter and verify resolution (15 min)
- In
AndroidManifest.xml, add aDeepLinkActivitywithandroid:exported="true"and an<intent-filter>containingandroid.intent.action.VIEW,android.intent.category.DEFAULT,android.intent.category.BROWSABLE, and<data android:scheme="learnandroid" android:host="items" />. (A custom scheme needs no domain verification, so it is easy to test.) - In
DeepLinkActivity, readintent.datainonCreateand loguri.lastPathSegmentwithLog.d. - Install the app and run
adb shell am start -W -a android.intent.action.VIEW -d "learnandroid://items/7". ConfirmDeepLinkActivityopens and the log shows7. - Remove the
DEFAULTcategory, reinstall, and run the same command. Confirm it no longer resolves, then put the category back. - In
MainActivity, add a button that launchesDeepLinkActivitywith an explicit intent throughregisterForActivityResult(ActivityResultContracts.StartActivityForResult()). InDeepLinkActivity, add a button that callssetResult(RESULT_OK)andfinish().
Done condition: The adb command opens DeepLinkActivity and logs 7, removing DEFAULT breaks it, and the result callback in MainActivity receives RESULT_OK.