Runtime permissions
Why it matters
- Every camera, mic, location, or notification feature in a real app depends on getting this flow right; calling a protected API without the permission throws
SecurityException. - Android 13 and 14 changed the rules (granular media permissions, the new notification permission, partial photo access), so old code can silently stop working when you raise
targetSdk. - Interviewers probe the difference between denied and permanently denied, and whether you know when registerForActivityResult can be called.
- Permission bugs show up in support tickets as 'feature stopped working after an update' and are hard to reproduce without a clean install.
The simple explanation
- You walk into a building with a keycard (install-time / normal permission).
- A restricted room needs a guard who asks the owner before letting you in (runtime / dangerous permission).
- The guard can say 'no' once and let you try again later (denied, rationale shown).
- After two 'no's the guard writes your name on a list and won't ask again (permanently denied).
- To get back in, you must go to the front desk (Settings) and update the list yourself.
Since Android 6.0 (API 23), for apps targeting API 23 or higher, dangerous permissions are no longer granted at install time. The app must ask while it is running, and the user can revoke them in Settings at any time.
The three states
| State | How to detect | What to do |
|---|---|---|
| Granted | ContextCompat.checkSelfPermission returns PERMISSION_GRANTED | Use the feature |
| Denied, can ask again | shouldShowRequestPermissionRationale returns true | Show a rationale dialog, then call launch() again |
| Permanently denied | Right after a denial in the result callback, shouldShowRequestPermissionRationale returns false | Explain, and offer a button to Settings.ACTION_APPLICATION_DETAILS_SETTINGS |
The request flow
- Call
ContextCompat.checkSelfPermission(context, permission)before using the feature. - If not granted, call
launcher.launch(permission)wherelauncheris created withregisterForActivityResult(ActivityResultContracts.RequestPermission()). The callback receives aBoolean. - For multiple permissions use
ActivityResultContracts.RequestMultiplePermissions(), which returns aMap<String, Boolean>.
Timing rule: registerForActivityResult must be called before the owning ComponentActivity or Fragment is STARTED. In practice that means a field initializer or onCreate. In Compose, call rememberLauncherForActivityResult unconditionally in the screen, so the launcher stays registered while the system dialog is open.
Android 13+ changes: for apps targeting API 33+, READ_EXTERNAL_STORAGE no longer grants media access on Android 13+. Use READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and READ_MEDIA_AUDIO instead. POST_NOTIFICATIONS is a new runtime permission. Android 14 adds READ_MEDIA_VISUAL_USER_SELECTED for partial photo access. Request the new names on API 33+ and keep READ_EXTERNAL_STORAGE (with maxSdkVersion="32") for older versions. If you only need the user to pick photos, the Photo Picker needs no permission at all.
Notes
- Normal vs dangerous:
INTERNETandVIBRATEare normal permissions, granted at install.CAMERA,RECORD_AUDIO,ACCESS_FINE_LOCATIONandBLUETOOTH_CONNECT(API 31+) are dangerous and need runtime consent. - Permission groups: the dialog is shown per group, but you must still request every permission you need. Since Android 8.0 a permission is not granted just because another one in its group was. If the group is already granted, a request for another permission in it is granted without a dialog.
- Location on Android 12+: request
ACCESS_FINE_LOCATIONandACCESS_COARSE_LOCATIONtogether. The user can choose approximate only, so handle coarse-only results. - shouldShowRequestPermissionRationale returns
falsewhen the permission was never requested, when it is granted, and when the user denied it permanently. On Android 11+, denying twice counts as "don't ask again"; earlier versions show a checkbox. - registerForActivityResult timing: call it in a field initializer or
onCreate. Calling it once the owner isSTARTED(inonStartoronResume, for example) throwsIllegalStateException. - Permanently denied: there is no API that returns it directly. The reliable check is in the result callback: the permission was denied and
shouldShowRequestPermissionRationaleis nowfalse. In that statelaunch()returnsfalseimmediately with no dialog, so offer Settings instead. - Android 13 media split:
READ_MEDIA_IMAGESandREAD_MEDIA_VIDEOshare one "photos and videos" dialog when requested together;READ_MEDIA_AUDIOhas its own. Check the result for each permission you requested. - POST_NOTIFICATIONS (API 33+): if it is not granted,
NotificationManagerCompat.notify()posts nothing. No crash, but the user sees nothing. Check withcheckSelfPermissionorareNotificationsEnabled()and ask at a moment where the value is clear. - Partial photo access (API 34+): the user can choose "Select photos and videos". Then
READ_MEDIA_VISUAL_USER_SELECTEDis granted butREAD_MEDIA_IMAGESis not, and MediaStore queries return only the selected items. Re-check on every resume and let the user change the selection. - Compose: call
rememberLauncherForActivityResultunconditionally. If it leaves the composition while the system dialog is open (for example it was inside anifthat flipped), the result is not delivered. - Settings intent: use
Settings.ACTION_APPLICATION_DETAILS_SETTINGSwithUri.fromParts("package", packageName, null). Re-check the permission inonResumewhen the user comes back. - Revocation: users can revoke a permission in Settings, and Android 11+ auto-resets permissions of unused apps. Never cache "granted"; check every time before using the feature.
Code example
This Activity requests the CAMERA permission through the Activity Result API, checks the three states, and routes the user to Settings when the permission is permanently denied.
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class CameraActivity : AppCompatActivity() {
// Field initializer: registered before the activity is STARTED.
private val cameraLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) {
openCamera()
} else {
handleCameraDenied()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
findViewById<Button>(R.id.btnCapture).setOnClickListener {
requestCamera()
}
}
private fun requestCamera() {
// 1. Already granted? Use it immediately.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED
) {
openCamera()
return
}
// 2. Denied before but can ask again? Explain first, then ask.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
showRationaleDialog() // on OK: cameraLauncher.launch(Manifest.permission.CAMERA)
return
}
// 3. Never asked, or permanently denied: launch. If permanently denied,
// no dialog appears and the callback receives false at once.
cameraLauncher.launch(Manifest.permission.CAMERA)
}
private fun handleCameraDenied() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
// Denied, but we may ask again later. Keep the rest of the app usable.
return
}
// Just denied and no rationale allowed: permanently denied.
// Explain, and let the user choose to open Settings.
AlertDialog.Builder(this)
.setMessage("Camera access is off. You can turn it on in Settings.")
.setPositiveButton("Open settings") { _, _ ->
startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.fromParts("package", packageName, null))
)
}
.setNegativeButton("Not now", null)
.show()
}
private fun openCamera() { /* start CameraX use case */ }
private fun showRationaleDialog() { /* explain why camera is needed */ }
}- The launcher is a field initializer, so it is registered before the activity is
STARTED. Moving it intoonResumewould throwIllegalStateException. handleCameraDeniedchecks the rationale after a denial.truemeans a normal denial;falseright after a denial means permanently denied, so the app offers Settings instead of a dialog that will never appear.shouldShowRequestPermissionRationaleis also checked beforelaunch(), so after one denial the app explains why it needs the camera before asking again.ActivityCompat.shouldShowRequestPermissionRationaleis used so the code is safe on every API level.
Run the idea in plain Kotlin
enum class PermState { GRANTED, DENIED, PERMANENTLY_DENIED }
class PermManager {
private val states = mutableMapOf<String, PermState>()
private val denyCount = mutableMapOf<String, Int>()
private val maxDenies = 2
fun check(name: String): PermState {
return states[name] ?: PermState.DENIED
}
fun request(name: String): PermState {
val cur = states[name] ?: PermState.DENIED
if (cur == PermState.GRANTED) return PermState.GRANTED
if (cur == PermState.PERMANENTLY_DENIED) return PermState.PERMANENTLY_DENIED
val n = (denyCount[name] ?: 0) + 1
denyCount[name] = n
val newState = if (n >= maxDenies) PermState.PERMANENTLY_DENIED else PermState.DENIED
states[name] = newState
return newState
}
fun grant(name: String) {
states[name] = PermState.GRANTED
denyCount[name] = 0
}
fun showRationale(name: String): Boolean {
return states[name] == PermState.DENIED
}
}
fun main() {
val pm = PermManager()
println("Initial: " + pm.check("CAMERA"))
println("Deny 1: " + pm.request("CAMERA"))
println("Rationale? " + pm.showRationale("CAMERA"))
println("Deny 2: " + pm.request("CAMERA"))
println("Rationale? " + pm.showRationale("CAMERA"))
println("Deny 3: " + pm.request("CAMERA"))
pm.grant("CAMERA")
println("After grant: " + pm.check("CAMERA"))
println("Rationale? " + pm.showRationale("CAMERA"))
}Expected output:
Initial: DENIED
Deny 1: DENIED
Rationale? true
Deny 2: PERMANENTLY_DENIED
Rationale? false
Deny 3: PERMANENTLY_DENIED
After grant: GRANTED
Rationale? false
Note that "Rationale?" is false both before any request and after the second denial. That is the same ambiguity the real API has, and why you check it right after a denial.
In production
- Crash reports showed
SecurityExceptionfromFusedLocationProviderClient.requestLocationUpdatesfor a small group of long-time users. - The app asked for location once during onboarding and saved
locationGranted = truein SharedPreferences. Later screens checked that flag instead of the real permission. - Users who later revoked location in Settings, or whose permissions Android 11+ auto-reset because the app was unused for months, crashed when they opened the map.
- Reproduced by granting location, revoking it in Settings, and opening the map screen.
- Removed the saved flag. Every location call now goes through one wrapper that calls
checkSelfPermissionfirst and requests the permission if it is missing. - Added a test for the wrapper with the permission denied, asserting that no location request is made.
- Enabled the lint check
MissingPermissionas an error so unguarded calls fail the build.
- After raising
targetSdkto 33, users on Android 13+ could no longer choose photos in the app's custom gallery. - The manifest still declared
READ_EXTERNAL_STORAGE; the code checked that permission withcheckSelfPermission. - For an app targeting API 33+,
READ_EXTERNAL_STORAGEgrants nothing on Android 13+, so the request showed no dialog and the check always returnedPERMISSION_DENIED.
- Declared
READ_MEDIA_IMAGESandREAD_MEDIA_VISUAL_USER_SELECTED, keptREAD_EXTERNAL_STORAGEwithmaxSdkVersion="32", and chose the permission to request withBuild.VERSION.SDK_INT. - Handled partial access on Android 14: when only
READ_MEDIA_VISUAL_USER_SELECTEDis granted, the gallery shows the selected photos and a button to select more. - For the simple profile-photo flow, switched to the Photo Picker (
PickVisualMedia), which needs no permission. - Added a CI matrix test on API 33 and 34 emulators to catch future permission renames.
Common mistakes
- Calling registerForActivityResult in onStart or onResume. The owner is already
STARTED, so the call throwsIllegalStateException. Register the launcher as a field initializer or inonCreate. - Treating shouldShowRequestPermissionRationale == false as 'permanently denied'. It also returns false when the permission was never requested. Only treat it as permanent when it is false right after a denial in the result callback.
- Requesting all permissions at app start. Users see a wall of dialogs and deny everything. Request each permission at the point of use, with a short rationale, so the user understands why.
- Using the deprecated onRequestPermissionsResult. It is deprecated in
ComponentActivityandFragmentand spreads result handling across request codes. UseregisterForActivityResultorrememberLauncherForActivityResult, which deliver the result to the right callback after rotation and process death. - Caching "granted". Users can revoke permissions in Settings, and Android 11+ auto-resets them for unused apps. Check with
checkSelfPermissionevery time before using the feature. - Not handling POST_NOTIFICATIONS on API 33+. Without the permission,
NotificationManagerCompat.notify()posts nothing. The app does not crash, so the problem is easy to miss without a test on Android 13+.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Walk through the runtime permission flow for a dangerous permission like CAMERA.”
“What does shouldShowRequestPermissionRationale return, and why is it confusing?”
“How do you handle media permissions after Android 13?”
“What happens if you call registerForActivityResult in onResume instead of onCreate?”
Quiz
When are dangerous permissions like CAMERA granted?
CAMERA is not granted and shouldShowRequestPermissionRationale returns false. What can you conclude?
What does the callback of ActivityResultContracts.RequestPermission() return?
Which permission was introduced as a runtime permission in Android 13 (API 33)?
0 of 4 answered
Mini task
Exercise: Camera permission with Settings fallback (15 min)
- Open your project's
AndroidManifest.xmland add<uses-permission android:name="android.permission.CAMERA" />. - In your main
Activity(orFragment), add a field:private val cameraLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> ... }. - In the callback, if
grantedis true, print a log or show a Toast. If false, callhandleDenied(). - Add a
Buttonin your layout. On click, callContextCompat.checkSelfPermission. If granted, show a Toast. If not, callcameraLauncher.launch(Manifest.permission.CAMERA). - In
handleDenied(), checkshouldShowRequestPermissionRationale. If it returnstrue, show anAlertDialogexplaining why the camera is needed, and on OK callcameraLauncher.launch(Manifest.permission.CAMERA)again. If it returnsfalse, the denial is permanent: show a dialog with an "Open settings" button that startsSettings.ACTION_APPLICATION_DETAILS_SETTINGSwith the package URI. - Run the app on an API 33+ emulator. Tap the button, deny the permission twice, and confirm the second denial shows the Settings dialog. Grant the permission in Settings, come back, and tap the button again.
Done condition: First tap shows the system dialog. Denying once shows your rationale dialog. Denying again shows the dialog that leads to the app's Settings page. Granting the permission shows the success Toast.