Intents and intent filters

Learn how Android Intents and intent filters work, including package visibility, exported rules, and how to handle component resolution. About 25 minutes.

Why it matters

  • Every screen transition, share action, deep link, and notification tap goes through an Intent. A wrong filter or a wrong android:exported value 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 raise targetSdk.
  • PendingIntent mutability 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:pathPattern means 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. startActivity adds CATEGORY_DEFAULT to implicit intents, so an activity filter needs DEFAULT to receive them.
  • Data: the intent's URI and MIME type must match the filter's <data> elements.

Key flags and attributes:

ItemWhat it controlsPitfall
android:exportedWhether other apps can start the componentRequired with intent filters when targeting API 31+; omitting it fails the build
android:autoVerifyAsks the system to verify App Links (HTTPS links)Needs /.well-known/assetlinks.json on your domain
<queries> elementWhich other apps your app can see through PackageManager (target API 30+)Without it, queryIntentActivities leaves those apps out
PendingIntent mutabilityFLAG_IMMUTABLE vs FLAG_MUTABLERequired 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.

Explicit goes straight there, implicit gets matched
How Android resolves an Intent An intent with a component set starts that exact component; an implicit intent is matched against intent filters by action, category and data, then nothing matching throws ActivityNotFoundException, one match opens directly, and several matches show a dialog where the user chooses. YES NO NONE MANY ONE startActivity(intent) action · data · extras Component set? Starts that class explicit, no filters Match intent filters action · category · data How many activities match? Throws ActivityNotFoundException User chooses unless a default is set Opens directly no dialog
Android only checks intent filters when the intent names no component. The number of matches decides what the user sees.

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 declare android:exported. The build fails if it is missing.
  • Package visibility applies when you target API 30+. queryIntentActivities, resolveActivity and getPackageInfo only see apps you declared in <queries> (plus a few always-visible ones). Prefer a narrow <intent> query over QUERY_ALL_PACKAGES, which Google Play restricts.
  • When targeting API 31+, every PendingIntent needs FLAG_IMMUTABLE or FLAG_MUTABLE. Use FLAG_IMMUTABLE unless 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 PendingIntent must 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 (and pathSuffix, pathAdvancedPattern on API 31+). pathPattern is a simple pattern where only . and * are special, not a full regex.
  • android:autoVerify="true" on an https filter asks the system to verify your domain through assetlinks.json. Verified links open your app directly. On Android 12+, unverified web links open in the browser by default.
  • FLAG_ACTIVITY_CLEAR_TOP together with FLAG_ACTIVITY_SINGLE_TOP brings an existing instance to the top of its task and delivers the new intent to onNewIntent. With CLEAR_TOP alone, a standard activity 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>
  • registerForActivityResult is safe to call as a field initializer or in onCreate. Calling it once the Activity is already STARTED throws IllegalStateException.
  • PickItemActivity returns its answer with setResult(RESULT_OK, Intent().putExtra(EXTRA_ITEM_ID, id)) and then finish().
  • ItemActivity reads the link in onCreate from intent.data, and in onNewIntent if 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

Custom share picker empty after raising targetSdk to 30
  • After raising targetSdk to 30, users saw an empty list in the app's own "Share to" bottom sheet.
  • Logs showed no exception; queryIntentActivities simply returned an empty list.
  • The app built its picker from queryIntentActivities for ACTION_SEND with type text/plain, but had no <queries> declaration, so other apps were invisible to it.
The fix
  • Added a <queries> block with an <intent> child matching ACTION_SEND and text/plain.
  • Verified on an Android 11+ device that the picker lists other apps again.
  • Turned on the lint check QueryPermissionsNeeded as an error, and considered replacing the custom picker with Intent.createChooser, which needs no <queries> at all.
Notification crash after targeting Android 12
  • After raising targetSdk to 31, the app crashed as soon as it tried to post a notification.
  • The stack trace pointed at PendingIntent.getActivity, with IllegalArgumentException: targeting S+ requires FLAG_IMMUTABLE or FLAG_MUTABLE.
  • The PendingIntent was created with PendingIntent.FLAG_UPDATE_CURRENT only.
The fix
  • Added PendingIntent.FLAG_IMMUTABLE to every getActivity, getBroadcast and getService call (combined with FLAG_UPDATE_CURRENT where needed).
  • For the one inline-reply action that the system must fill in, used FLAG_MUTABLE with 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 true for launcher and deep-link activities, false otherwise.
  • Registering for an Activity result too late. registerForActivityResult must be called before the Activity (or Fragment) is STARTED, for example as a field or in onCreate. Calling it later, such as inside a click listener, throws IllegalStateException.
  • Forgetting the queries element when you query other apps. When targeting API 30+, queryIntentActivities, resolveActivity and getPackageInfo leave 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. Call startActivity and catch ActivityNotFoundException instead.
  • Creating a PendingIntent without a mutability flag. When targeting API 31+ this throws IllegalArgumentException. Use FLAG_IMMUTABLE unless 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 Intent straight to startActivity (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

  1. In AndroidManifest.xml, add a DeepLinkActivity with android:exported="true" and an <intent-filter> containing android.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.)
  2. In DeepLinkActivity, read intent.data in onCreate and log uri.lastPathSegment with Log.d.
  3. Install the app and run adb shell am start -W -a android.intent.action.VIEW -d "learnandroid://items/7". Confirm DeepLinkActivity opens and the log shows 7.
  4. Remove the DEFAULT category, reinstall, and run the same command. Confirm it no longer resolves, then put the category back.
  5. In MainActivity, add a button that launches DeepLinkActivity with an explicit intent through registerForActivityResult(ActivityResultContracts.StartActivityForResult()). In DeepLinkActivity, add a button that calls setResult(RESULT_OK) and finish().

Done condition: The adb command opens DeepLinkActivity and logs 7, removing DEFAULT breaks it, and the result callback in MainActivity receives RESULT_OK.

Next: Runtime permissions