Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 104 ยท Activities and the Lifecycle

Runtime Permissions

Learn Android runtime permissions: normal versus dangerous, the requestPermission contract, rationale and denial flows, and no-permission options like the photo picker.

Android apps run in a sandbox: by default, an app cannot read your contacts, record audio, see your location or open the camera. To do those things it needs a permission, and for the sensitive ones the user must say yes at the moment the app asks. A good permission flow is part of your app's quality: ask at the right time, explain why, and keep working when the user says no.

This lesson covers normal and dangerous permissions, the RequestPermission contract from the Activity Result API (which you met in Intents and Launching Other Screens), how to handle rationale and denial, and the options that avoid asking at all, such as the photo picker. Real permission code needs a device and a manifest, so the Android snippets are read-only. The TryIt blocks are stand-ins: a state machine that follows the system's rules for repeated requests, and a decision helper for choosing the right approach.

Declaring permissions

Every permission your app might use is declared in AndroidManifest.xml with <uses-permission>. Without the declaration, the system rejects the request automatically:

XML
<!-- read-only example: AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    ...
</manifest>

Permissions fall into groups by risk:

  • Normal permissions, such as INTERNET, ACCESS_NETWORK_STATE and VIBRATE, carry little risk for privacy. They are granted at install time without asking.
  • Dangerous (runtime) permissions give access to private data or sensor hardware: CAMERA, RECORD_AUDIO, ACCESS_FINE_LOCATION, READ_CONTACTS, POST_NOTIFICATIONS (Android 13+) and similar. Declaring them is not enough: you must ask the user while the app runs.
  • Special permissions, such as drawing over other apps or scheduling exact alarms, are granted from a dedicated screen in system settings, not through a normal dialog.

Asking with the Activity Result API

The request is an Activity Result contract. In Compose, you create a launcher with rememberLauncherForActivityResult, launch it from an event such as a button click and handle the answer in the callback:

Kotlin
// read-only example: Compose, camera permission
@Composable
fun CameraEntry(onGranted: () -> Unit) {
    val context = LocalContext.current
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (granted) onGranted() else { /* show an explanation, offer alternatives */ }
    }

    Button(onClick = {
        val already = ContextCompat.checkSelfPermission(
            context, Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
        if (already) onGranted() else launcher.launch(Manifest.permission.CAMERA)
    }) {
        Text("Scan a code")
    }
}

The order is always: check, then ask. checkSelfPermission returns granted or denied without showing anything. Call launch only when it is denied. For several permissions at once (for example coarse and fine location) use ActivityResultContracts.RequestMultiplePermissions(), which returns a map of permission to result. On Android 12 and later the user may grant only approximate location even if you ask for precise, so your app must work with the coarse result.

When to ask

Ask in context, at the moment the user does something that needs the permission: the camera when they tap "Scan", the microphone when they tap the record button. Do not request everything on the first launch: users deny a request they do not understand, and the system may stop showing dialogs after repeated denials. If the permission is optional for the feature, say what the user gets (and keep the rest of the app usable).

Rationale and denial

What happens after a "No" matters. The system follows these rules (Android 11 and later):

  1. First request: the dialog appears. If the user taps Allow (or While using the app), you are done.
  2. If the user denies once, the next launch shows the dialog again, and before that shouldShowRequestPermissionRationale(...) returns true. This is your chance to explain why you need it, with your own UI, before asking again.
  3. If the user denies a second time, the system treats it as "don't ask again". Further launch calls complete immediately with denied and no dialog. The only way forward is to send the user to your app's settings screen and let them enable the permission there.
  4. For some permissions the dialog has a one-time option ("Only this time"). The permission is revoked again when the app goes to the background, so always check before use rather than remembering a grant.
stateDiagram-v2
    [*] --> NotAsked
    NotAsked --> Granted: user allows
    NotAsked --> DeniedOnce: user denies
    DeniedOnce --> Granted: rationale shown, user allows
    DeniedOnce --> PermanentlyDenied: user denies again
    PermanentlyDenied --> Granted: user enables it in Settings
    Granted --> [*]

After the second denial the system stops asking, and only the Settings screen can grant it.

The stand-in below follows exactly these rules. The "user" is a list of answers, so the run is deterministic. When the system will no longer show a dialog, request says so.

Kotlin A permission request state machine (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.

A well-behaved app turns this into UI: on the first denial show a short message about the benefit; on "permanently denied" show a button that opens settings with Settings.ACTION_APPLICATION_DETAILS_SETTINGS; and in every case keep the rest of the app working.

Kotlin
// read-only example: open this app's settings page
val intent = Intent(
    Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
    Uri.fromParts("package", context.packageName, null)
)
context.startActivity(intent)

The best permission is no permission

Many features that used to need a permission now have an alternative that needs none, and users trust apps that need fewer permissions:

  • Pick photos or videos with the photo picker (ActivityResultContracts.PickVisualMedia). The user selects the items in a system UI and your app receives access only to those. No READ_MEDIA_IMAGES is needed.
  • Pick any file with OpenDocument or GetContent (the system file picker, part of the Storage Access Framework).
  • Take a photo with ActivityResultContracts.TakePicture: the camera app does the work and returns the picture, so your app needs no CAMERA permission. You need CAMERA only for your own live preview, as in a code scanner.
  • Save your own files in your app's private storage: no permission. See Files, Scoped Storage and Media.
  • Dial with ACTION_DIAL instead of ACTION_CALL: the user presses the call button, and you need no CALL_PHONE.
Kotlin
// read-only example: choosing a photo without any permission
val pickMedia = rememberLauncherForActivityResult(
    ActivityResultContracts.PickVisualMedia()
) { uri: Uri? ->
    // uri is null if the user cancelled
}

Button(onClick = {
    pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}) { Text("Choose a photo") }

The next stand-in is a small advisor. It takes what a feature wants to do and answers with the lowest-friction approach. The rules are the ones listed above, written as a lookup, and it also checks that the manifest declares anything a runtime request needs.

Kotlin Choosing the least-permission approach (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.

Permission helper libraries

Before the Activity Result API, permission code was long: checkSelfPermission, requestPermissions, an onRequestPermissionsResult override and a request code to match answers. Libraries such as Dexter wrapped that in a fluent builder and a listener (onPermissionGranted, onPermissionDenied, onPermissionRationaleShouldBeShown). They were popular in tutorials, but most are no longer maintained and the platform API now does the job in a few lines (see "Asking with the Activity Result API" above). If you inherit an old project, you will meet two styles:

Kotlin
// read-only example: the legacy callback style you may need to read
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == REQUEST_CAMERA && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
        openCamera()
    }
}

Migrate it to registerForActivityResult(ActivityResultContracts.RequestPermission()), which removes the request code and keeps the callback next to the request. In Compose you can wrap the same contract in a small helper composable that you write once and reuse.

Privacy and trust

  • Request the minimum. Ask for coarse location if a city-level result is enough. Ask for a permission only when a feature that the user chose needs it.
  • Explain before the dialog, in your UI, in plain language. Do not explain with text that is unrelated to what the permission does.
  • Re-check every time. The user can revoke a permission in settings at any moment, and the system may auto-reset permissions of apps that go unused for months. Never cache "granted" in a variable or in storage.
  • Handle "denied" as a normal state, not an error. Provide a manual alternative, for example typing a city instead of using location.
  • Notifications: since Android 13 POST_NOTIFICATIONS is a runtime permission. Services, Notifications and Foreground Work shows how to ask for it at a sensible moment.
  • Declare accurately in Google Play's data safety form what you collect, and remove permissions you no longer use. Libraries can add permissions to your manifest through manifest merging, so read the merged manifest in Android Studio.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is a normal permission that is granted at install time without asking?

    INTERNET is a normal permission with low privacy risk, granted automatically. Camera, microphone and contacts are dangerous permissions that need a runtime request.
  2. 2. What is the correct order when your feature needs a dangerous permission?

    Use checkSelfPermission first. Only if it is denied should you launch the request. Never cache the result, because the user can revoke it at any time.
  3. 3. After the user denies a permission twice on a modern Android version, what does launch do?

    The system treats a second denial as don't ask again. The only route to the permission is the app's settings screen, which you can open with an intent.
  4. 4. How can an app let the user attach a photo without holding any storage permission?

    The photo picker is a system UI that returns only the items the user selects, so the app needs no media permission.

Summary

  • Normal permissions are granted at install; dangerous ones need a runtime request, and special ones go through Settings.
  • Declare every permission in the manifest, then check with checkSelfPermission and launch RequestPermission only when needed.
  • Ask in context, explain with your own rationale after the first denial, and expect "don't ask again" after the second.
  • Send the user to the app's settings screen when the system will no longer show the dialog.
  • Prefer approaches that need none: photo picker, document picker, TakePicture, ACTION_DIAL, app-private storage.
  • Treat denial as a normal state, re-check each time and request the minimum.
  • The Android code is read-only; the TryIts are stand-ins for the request state machine and the decision rules.

Next: Thinking in Compose