skip to content

On Android, how do you request the camera permission with the RequestPermission contract, including the rationale and the denial paths?

level: middleimportance: must knowfreq 82%

answer

  1. ask in context, not at launch
  2. check, explain, then launch
  3. register before the activity is created
  4. two denials end the dialog

basics

~10 s

Declare CAMERA, check it with ContextCompat.checkSelfPermission, show your own explanation when shouldShowRequestPermissionRationale returns true, then launch a RequestPermission launcher and handle its boolean. A denial degrades the feature; denying twice stops the dialog appearing.

solid answer

~40 s

I declare `CAMERA` with `<uses-permission>` and ask only when the user taps the camera button. In the click handler I call `ContextCompat.checkSelfPermission()`; `PERMISSION_GRANTED` means go ahead. Otherwise, if `shouldShowRequestPermissionRationale()` returns `true`, I show my own explanation with a way to decline, and only then request. The request itself is an `ActivityResultLauncher` from `registerForActivityResult(ActivityResultContracts.RequestPermission())`, registered before the activity is created and launched once its lifecycle is at least `CREATED`; the callback gets `isGranted`. The system dialog can't be customised. On denial I degrade gracefully, disabling only the camera path and saying so where the photo would appear. If the user denies twice during the install, the system stops showing the dialog, so asking in context matters. And I check again before every use, because the user can revoke the grant.

code

kotlin · 35 lines
kotlin
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class ComposePostActivity : ComponentActivity() {

    // Registered as a property, before the activity is created.
    private val cameraPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) openInAppCamera() else showCameraUnavailable()
        }

    // Called when the user taps "Take photo" in the post composer.
    fun onTakePhotoClicked() {
        when {
            ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED -> openInAppCamera()

            ActivityCompat.shouldShowRequestPermissionRationale(
                this, Manifest.permission.CAMERA
            ) -> showCameraRationale(
                onContinue = { cameraPermission.launch(Manifest.permission.CAMERA) }
            )

            else -> cameraPermission.launch(Manifest.permission.CAMERA)
        }
    }

    private fun openInAppCamera() { /* start the camera preview */ }
    private fun showCameraUnavailable() { /* inline message; text posts still work */ }
    private fun showCameraRationale(onContinue: () -> Unit) { /* "Continue" and "No thanks" */ }
}

go deeper

for a junior

Know the order: declare in the manifest, check with checkSelfPermission, explain if needed, request, then handle a yes or a no.

for a middle

Explain the RequestPermission contract and its lifecycle rules, what the rationale check is for, and why two denials end the dialog for the install.

for a senior

Show how you keep the app usable after denial and revocation, and how you verify the denied, permanently denied and one-time states on a device.

for a principal

Treat the ask as a one-shot budget: a lead decides where in the flow each prompt appears, because asking too early can lose a feature permanently.

## The flow the platform expects Android's runtime permission flow has a fixed order, and interviewers usually want to hear it step by step: 1. **Declare** the permission in `AndroidManifest.xml` with `<uses-permission android:name="android.permission.CAMERA" />`. 2. **Wait for the user's action.** Ask when the user taps "Take photo", not at app start. Android's guidance is to ask *in context*, as late as possible in the flow. 3. **Check** with `ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)`. It returns `PackageManager.PERMISSION_GRANTED` or `PERMISSION_DENIED`. 4. **Explain if the system says so.** Call `shouldShowRequestPermissionRationale()` (through `ActivityCompat`, or on the activity or fragment). If it returns `true`, show your own educational UI explaining what the camera is for and what will not work without it, with a "No thanks" option that does not block the user. 5. **Request** through an `ActivityResultLauncher`. 6. **Handle the answer**: use the camera if granted, degrade gracefully if not. The worked example in the code block follows exactly this `when` ladder. ## RequestPermission and the Activity Result API The recommended way to request is the **`RequestPermission`** contract from `androidx.activity` (1.2.0 or later; `androidx.fragment` 1.3.0 or later for fragments), with **`RequestMultiplePermissions`** for several permissions at once. You pass the contract to `registerForActivityResult()`, keep the returned launcher, and call `launch(Manifest.permission.CAMERA)`; the system shows its dialog and later calls your `ActivityResultCallback` with a boolean. Two lifecycle rules matter (the Activity Result API itself is covered with activities and fragments): - **Register early.** `registerForActivityResult()` must be called *before* the activity or fragment is created, which is why it is usually a property initializer. - **Launch later.** You can't call `launch()` until the lifecycle has reached `CREATED`. The older path, `requestPermissions()` with your own request code and an `onRequestPermissionsResult()` override, still works; the contract simply lets the system manage the request code. ## What you can and cannot change in the dialog You **cannot customise** the system dialog. Its text names the permission group, not your reason. So the explanation lives in your UI: the rationale screen, the wording of the button that triggers the request, or a note in the composer. Android 12 (API 31) and higher also show a privacy indicator whenever an app uses the camera or microphone. ## The denial paths | Situation | What the platform does | What the app should do | |---|---|---| | First denial | Callback receives `false` | Keep the app usable; show a specific message where the photo would appear | | Rationale due | `shouldShowRequestPermissionRationale()` returns `true` | Show the educational UI, with a way to decline, before requesting again | | Denied more than once in this install | The system no longer shows the dialog; the request comes back denied | Stop prompting; keep the degraded path; respect the decision | | Revoked later in settings | The app's process is terminated | On next use, the check fails and the flow starts again | | "Only this time" (Android 11 / API 30, camera, microphone, location) | Grant lapses after the app leaves the foreground for a while | Nothing special if you already check before each use | The guidance on denial is firm: - **Minimise functionality loss.** A social app whose camera is denied must still let people write text posts and pick images another way. - **Be specific.** Say which feature is unavailable, where it would have appeared. - **Don't block.** No full-screen warning that stops the user. - **Don't nag.** The documentation's own sample says not to link to system settings in an effort to convince the user to change their decision. Because two denials make the denial permanent for the install, asking at the wrong moment (at launch, before the user knows why) can cost the feature for good. ## Debugging the state While testing, `adb shell dumpsys package <package>` lists each runtime permission with flags: `USER_SET` after one denial, `USER_FIXED` after a permanent one. `adb shell pm clear-permission-flags <package> <permission> user-set user-fixed` resets them so testers see the dialog again. ## Common mistakes - Requesting every permission in `onCreate()` of the first screen. - Registering the launcher inside the click handler, after the activity was created. - Treating a grant as permanent and skipping the check on later uses. - Re-launching the request in a loop after a denial.

  • What happens to a running app when the user revokes its camera permission in system settings?
    The system terminates the app's process. The next time the user reaches the camera feature, `checkSelfPermission()` returns `PERMISSION_DENIED` and the app has to go through the request flow again. This is one reason the guidance is to check before every access rather than cache an earlier answer.
  • How do you see, while debugging, whether a permission was denied once or permanently?
    Run `adb shell dumpsys package <package>` and read the runtime permissions section. A permission denied once carries the `USER_SET` flag; one denied permanently carries `USER_FIXED`. To make the dialog appear again for testers, clear both with `adb shell pm clear-permission-flags <package> <permission> user-set user-fixed`.
  • What does the app need to change to support the 'Only this time' choice?
    Usually nothing. On Android 11 (API 30) and higher, location, microphone and camera requests offer it; the app keeps access while its activity is visible and briefly after it goes to the background, or until a foreground service started while visible stops. The next session prompts again. An app that already checks before each use handles it.

  • Ask for every permission the app needs at first launch so the user decides once.
  • You can put your own reason text into the system permission dialog.
  • After a denial, launch the request again until the user says yes.
  • Registering the permission launcher inside the click handler is fine.
  • If the check passed at startup, later camera uses need no check.

Assumes Android 17 (API 37) with androidx.activity 1.2.0 or later; runtime requests apply since Android 6.0 (API 23) and one-time grants since Android 11 (API 30).