Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 104 ยท Activities and the Lifecycle

Intents and Launching Other Screens

Learn Android intents: explicit and implicit intents, extras, intent filters, the Activity Result API, and how to share content or open links safely.

Android apps are made of separate components that do not call each other directly. When one screen wants to open another, send an email, share a photo or open a web page, it describes what it wants in a message called an Intent and hands that message to the system. The system finds a component that can handle it, starts it, and, if you asked for it, brings a result back.

This lesson covers the two kinds of intents, extras, intent filters, the Activity Result API and the common built-in actions such as sharing and opening links. The real classes (Intent, startActivity) need the Android SDK, so the Android snippets are read-only. The TryIt blocks are stand-ins: an intent resolver that matches filters the way the system does, and a model of the Activity Result API. In a single-activity Compose app you will use navigation between your own screens and intents mainly to reach other apps and system screens, but they are still the foundation of everything on this page. Before this lesson, read Activities and setContent and The Activity Lifecycle.

Explicit intents

An explicit intent names the exact component to start. You use it for screens inside your own app:

Kotlin
// read-only example: needs the Android SDK
val intent = Intent(this, DetailActivity::class.java).apply {
    putExtra("note_id", 42L)
    putExtra("title", "Shopping list")
}
startActivity(intent)

The target activity reads the extras:

Kotlin
// read-only example
class DetailActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val noteId = intent.getLongExtra("note_id", -1L)
        val title = intent.getStringExtra("title") ?: "Untitled"
        setContent { DetailScreen(noteId, title) }
    }
}

Extras are key-value pairs stored in a Bundle. They can hold primitives, strings, arrays and Parcelable or Serializable objects. Two rules keep you out of trouble. First, pass identifiers and small values, not large objects: the data crosses a process boundary and a transaction larger than about 1 MB fails with a TransactionTooLargeException. Second, put your keys in constants so the sender and the receiver cannot disagree on a typo.

Implicit intents

An implicit intent does not name a component. It states an action (what to do) and, usually, data (what to do it on), and Android finds any app that has declared it can do that. You use it to open links, dial numbers, share text or pick a file:

Kotlin
// read-only example: open a web page
val openLink = Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/docs"))
try {
    startActivity(openLink)
} catch (e: ActivityNotFoundException) {
    // no app can handle it: tell the user instead of crashing
}

// read-only example: share text
val share = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_TEXT, "Check out this tutorial!")
}
startActivity(Intent.createChooser(share, "Share via"))

Always handle the case where nothing can answer, either with a try/catch for ActivityNotFoundException or by checking first. Since Android 11, apps cannot freely see which other apps are installed (package visibility), so checking first with resolveActivity also requires a <queries> element in your manifest. Catching the exception is simpler and works everywhere.

Intent.createChooser always shows the system chooser, so the user picks the target every time instead of getting a remembered default. Other very common actions are ACTION_DIAL (open the dialer with a number, no permission needed), ACTION_SENDTO with a mailto: URI, and Settings.ACTION_APPLICATION_DETAILS_SETTINGS to open your app's settings page.

Intent filters: how the system decides

Components advertise what they can handle with an intent filter in the manifest. When you fire an implicit intent, the system compares it with every filter of every installed app. A filter matches only if all three tests pass:

  1. Action: the intent's action is one of the filter's actions.
  2. Category: every category in the intent is listed in the filter. startActivity adds CATEGORY_DEFAULT to implicit intents, so a filter must include android.intent.category.DEFAULT to receive them.
  3. Data: the URI scheme (and host, path) and the MIME type match the filter's <data> entries. A filter without <data> only accepts intents without data.
XML
<!-- read-only example: an activity that can open web links to your site -->
<activity android:name=".LinkActivity" android:exported="true">
    <intent-filter>
        <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" android:host="example.com" />
    </intent-filter>
</activity>
flowchart TD
    A["Implicit Intent<br/>action + data + categories"] --> B{"Which filters match?"}
    B -->|"none"| C["ActivityNotFoundException"]
    B -->|"one"| D["Start that component"]
    B -->|"several"| E["Chooser: the user picks"]

The system resolves an implicit intent by matching it against every registered filter.

The stand-in below implements a simplified version of this matching: action, categories, URI scheme and MIME type (without host and path matching). It builds a few intents and prints which "apps" can handle each.

Kotlin An intent resolver (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 sharing text/plain produces a chooser (two apps), sharing video/mp4 finds nobody, and an action no one handles also finds nobody. Your app must be ready for the "nobody" case.

Getting a result back

Sometimes you start another screen to get something: a picture, a chosen file, a permission answer. The old API was startActivityForResult with onActivityResult, which is deprecated because it scattered one flow across two methods and a request-code switch. The replacement is the Activity Result API, which works through a contract: a typed pair of "how to build the intent from my input" and "how to turn the result into my output."

Kotlin
// read-only example: Compose, picking a document
@Composable
fun ImportButton(onPicked: (Uri?) -> Unit) {
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument()
    ) { uri: Uri? ->
        onPicked(uri)          // null if the user cancelled
    }
    Button(onClick = { launcher.launch(arrayOf("application/pdf")) }) {
        Text("Import a PDF")
    }
}

In an activity (not Compose) you register the launcher as a property, before the activity is STARTED, using registerForActivityResult. Never create one inside a click handler. The Compose helper rememberLauncherForActivityResult handles the registration for you. Ready-made contracts live in ActivityResultContracts: GetContent, OpenDocument, TakePicture, PickVisualMedia, RequestPermission and more. The permission one is the topic of Runtime Permissions.

The stand-in below models the pattern: a Contract<I, O> creates the intent from an input and parses the result, a registry connects a launcher to a callback, and a fake "other app" returns either a result or a cancellation.

Kotlin The Activity Result API as a model (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 important design idea is visible even in this small model: the caller deals with typed values (Int?), and the cancellation case is part of the type, so it cannot be forgotten.

Implicit intent recipes

Most implicit intents are one of a dozen patterns. Each one is an action, a data URI with the right scheme, and sometimes extras. The pattern is the same every time: build the intent, start it inside a try/catch, and tell the user if nothing handled it. All of the intents below start another app's screen and do not need a runtime permission, which is the main reason to prefer them over doing the work yourself.

Kotlin
// read-only example: one helper for every recipe
fun Context.startSafely(intent: Intent): Boolean = try {
    startActivity(intent)
    true
} catch (e: ActivityNotFoundException) {
    false
}

Dialer: ACTION_DIAL versus ACTION_CALL

Kotlin
// read-only example
val dial = Intent(Intent.ACTION_DIAL, Uri.parse("tel:+15551234567"))   // opens the dialer, user presses Call
val call = Intent(Intent.ACTION_CALL, Uri.parse("tel:+15551234567"))   // calls at once, needs CALL_PHONE

ACTION_DIAL only fills in the number and needs no permission; the user must press the call button. ACTION_CALL places the call immediately and requires the dangerous CALL_PHONE permission, which many users refuse and which Play review looks at closely. Use ACTION_DIAL unless calling directly is the app's core feature. Percent-encode + and # if they are in the number (Uri.encode), or build the URI with Uri.fromParts("tel", number, null).

SMS and email

Kotlin
// read-only example: a prefilled text message
val sms = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:+15551234567")).apply {
    putExtra("sms_body", "I'll be there at 6")
}

// read-only example: a prefilled email
val email = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")).apply {   // only email apps match
    putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
    putExtra(Intent.EXTRA_SUBJECT, "Bug report")
    putExtra(Intent.EXTRA_TEXT, "Steps to reproduce:\n1. ...")
}

Both open the other app's compose screen with your text already in it; the user reviews and sends. Sending an SMS silently (SmsManager) needs the restricted SEND_SMS permission and is not appropriate for most apps. For email, the ACTION_SENDTO with an empty mailto: URI is the trick that limits the chooser to mail apps; the older ACTION_SEND with type = "message/rfc822" also lists unrelated apps. Attachments go through EXTRA_STREAM with a FileProvider URI, see Content Providers.

Share sheet

The pattern from the section above, ACTION_SEND wrapped in Intent.createChooser, shares text. For an image or a file set type = "image/png", pass a content:// URI in EXTRA_STREAM and add FLAG_GRANT_READ_URI_PERMISSION; for several files use ACTION_SEND_MULTIPLE with a list. A chooser title is optional, and from Android 10 you can add a share title and thumbnail with EXTRA_TITLE.

Camera and image capture

Kotlin
// read-only example: the modern way, with the Activity Result API
val photoUri: Uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", photoFile)

val takePicture = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { saved ->
    if (saved) viewModel.onPhotoTaken(photoUri)       // the full-size image was written to photoUri
}
Button(onClick = { takePicture.launch(photoUri) }) { Text("Take photo") }

TakePicture wraps MediaStore.ACTION_IMAGE_CAPTURE, writes the full-size photo to the URI you provide (a FileProvider URI, so the camera app is allowed to write it) and returns a Boolean. TakePicturePreview returns only a small thumbnail Bitmap. Because the camera app takes the photo, your app needs no CAMERA permission, unless your own manifest declares it: in that case the system requires it to be granted before the camera intent works. For a camera preview inside your own screen use CameraX, see Permissions. To choose an existing photo, use PickVisualMedia, not a custom gallery.

Kotlin
// read-only example
val coordinates = Uri.parse("geo:48.8584,2.2945?z=16")                       // map centered on a point
val labelled = Uri.parse("geo:0,0?q=" + Uri.encode("Eiffel Tower, Paris"))   // search or a pin with a label
val map = Intent(Intent.ACTION_VIEW, labelled)

val page = Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/help"))

The geo: scheme opens whatever map app the user has; do not hard-code a vendor package. ACTION_VIEW with an https URL opens the default browser or, if an installed app verified that domain, that app. To keep users inside your app's look and feel, open pages in a Custom Tab (CustomTabsIntent.Builder().build().launchUrl(context, uri)) from AndroidX Browser.

Settings screens

Kotlin
// read-only example
val appSettings = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null))
val wifi = Intent(Settings.ACTION_WIFI_SETTINGS)
val locations = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
val notifications = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, packageName)

The app details screen is where you send a user who permanently denied a permission, so they can grant it by hand (see Runtime Permissions). Notification settings are the place to fix a channel the user switched off, see Services and Notifications. Settings intents are not guaranteed on every OEM build, so keep the try/catch.

Package visibility and <queries>

If you want to ask "can something handle this?" before showing a button, resolveActivity and queryIntentActivities only see apps that your manifest declares visible (Android 11 and higher):

XML
<!-- read-only example: lets this app see which apps can open https links and send email -->
<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="https" />
    </intent>
    <intent>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="mailto" />
    </intent>
</queries>

Without that block, the check silently reports nobody can handle the intent even if an app exists, so the button never appears. Starting the intent itself does not need <queries>. For that reason the shortest correct code is the startSafely helper above: try, and fall back to a message ("No email app found") when it fails. Keep <queries> narrow; Google Play restricts broad visibility such as QUERY_ALL_PACKAGES.

The next stand-in builds the intents for these recipes as plain data, so you can print the action, data URI and extras without an Android device. It uses the real java.net.URLEncoder for query text.

Kotlin Building implicit intents for the common recipes (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 second stand-in models the visibility trap: asking "can anything handle this?" is answered from the apps your manifest declares visible, while simply starting the intent works regardless.

Kotlin resolveActivity, queries and the safe fallback (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.

Security basics

Intents cross app boundaries, so treat anything that arrives in getIntent() as untrusted input from outside:

  • Set android:exported="false" on components that only your own app should start. Since Android 12 you must state exported explicitly for every component with an intent filter.
  • Validate extras and data from incoming intents before using them, as you would with web request parameters.
  • For intents handed to other apps through a notification or an alarm, use a PendingIntent with FLAG_IMMUTABLE unless you really need it to be mutable.
  • Never put secrets in extras of implicit intents: any app with a matching filter may receive them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between an explicit and an implicit intent?

    Explicit intents name a class and are used inside your app. Implicit intents state an action (and data), and the system matches them against intent filters.
  2. 2. An implicit intent has the category DEFAULT added by startActivity. What must the receiving filter contain to match?

    Every category of the intent must appear in the filter. Because startActivity adds DEFAULT, a filter without it cannot receive the intent.
  3. 3. Why should you wrap startActivity for an implicit intent in a try/catch?

    If no filter matches, the call throws ActivityNotFoundException. Catch it and tell the user instead of letting the app crash.
  4. 4. What replaced startActivityForResult and onActivityResult?

    The Activity Result API uses typed contracts and registered launchers, so the request and the callback stay together and there are no request codes.
  5. 5. What is the recommended thing to put in intent extras?

    Extras cross a process boundary with a limit of about 1 MB per transaction. Pass an id and load the real data from your repository, and never send secrets in implicit intents.

Summary

  • An Intent is a message to the system: an explicit intent names a component, an implicit one names an action and data.
  • Extras are small key-value pairs in a Bundle; pass ids, not large objects, and use constant keys.
  • Intent filters (action, category, data) decide which components can answer an implicit intent; handle the "nobody can" case.
  • Use Intent.createChooser for sharing, ACTION_VIEW for links and ACTION_DIAL for the dialer without permissions.
  • The implicit intent recipes (dial, SMS, email, share, camera, maps, settings) need no permission; check visibility with <queries>, or simply start the intent in a try/catch.
  • Get results with the Activity Result API: a typed contract plus a launcher registered early (rememberLauncherForActivityResult in Compose).
  • Treat incoming intents as untrusted input; set exported deliberately.
  • The Android code is read-only; the TryIts are stand-ins modeling filter matching and typed results.

Next: Configuration Changes and Saved State