Android Development

Tutorial: Requesting Runtime Permissions on Android 14: Guiding Users Past "Don't Ask Again"

Android applications often require access to sensitive user data or device capabilities, such as the camera, contacts, or location. Since Android 6.0 (API 23), users grant these runtime permissions dynamically while the app is running, rather than all at installation time. This shift prioritizes user privacy and control, but it also introduces complexity for developers.

A common pitfall in many permission tutorials is an incomplete strategy for handling user denials, especially when a user persistently refuses a permission request by selecting "Don't ask again." A basic implementation might simply disable features, but a robust app needs to guide users effectively when this happens, otherwise, they can get stuck in a state where a core feature is unavailable with no clear path to enable it.

This tutorial will guide you through building a resilient permission request flow for Android 14 (API 34) using the modern ActivityResult API. You will learn how to declare permissions, dynamically check their status, request them with user-friendly explanations, and most importantly, gracefully handle persistent denials by directing users to app settings. By the end, you'll have a clear, user-centric approach that ensures your app remains functional and intuitive even when permissions are initially denied.

Core Concepts: Modern Android Permissions

Before diving into the code, understand the core principles:

  • Runtime vs. Install-time Permissions: Permissions are categorized. Normal permissions are granted automatically at installation. Dangerous permissions (like camera, location) require explicit user consent at runtime. We are focusing on dangerous permissions.
  • targetSdkVersion and compileSdkVersion: Your build.gradle defines these. Setting compileSdk = 34 and targetSdk = 34 ensures your app is built against and targets Android 14 (current stable version at the time of writing). This guarantees you leverage the latest platform behaviors and APIs.
  • ActivityResult API: Introduced in androidx.activity:activity-ktx:1.2.0, this API simplifies handling results from other activities, including permission requests. It replaces older startActivityForResult patterns and is crucial for modern permission flows.
  • shouldShowRequestPermissionRationale(): A key method that helps determine if you should show an educational UI to the user. It returns true if the user has denied the permission at least once but has not selected "Don't ask again". This is your cue to explain why your app needs the permission before requesting it again.

Implementation Steps

We will implement a request for the CAMERA permission as an example. This approach is generalizable to other dangerous permissions.

Step 1: Declare Permissions in AndroidManifest.xml

All dangerous permissions your app might use must be declared in your manifest. This informs the Android system about your app's requirements.

XML
<!-- AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.CAMERA" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="34">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 2: Register the ActivityResultLauncher

In your Activity or Fragment, register a ActivityResultLauncher for requesting permissions. This should be done in your onCreate (or onViewCreated for Fragments) method, before the component is in the STARTED state.

Kotlin
// MainActivity.kt
package com.techlabindia.permissiondemo

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 android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

    private lateinit var statusTextView: TextView
    private lateinit var requestPermissionButton: Button

    // 1. Register the ActivityResultLauncher
    private val requestCameraPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            isGranted: Boolean ->
            if (isGranted) {
                // Permission is granted.
                updateUi("Camera permission granted!")
                // You can now access the camera
            } else {
                // Permission is denied.
                handlePermissionDenied()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        requestPermissionButton = findViewById(R.id.requestPermissionButton)

        requestPermissionButton.setOnClickListener { checkAndRequestCameraPermission() }

        // Initial UI update based on current permission state
        updatePermissionStatus()
    }

    private fun updateUi(message: String) {
        statusTextView.text = message
        // Optionally update button state or enable camera functionality
    }

    private fun updatePermissionStatus() {
        when {
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
                    PackageManager.PERMISSION_GRANTED -> {
                updateUi("Camera permission is currently GRANTED.")
            }
            shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA) -> {
                updateUi("Camera permission is DENIED (rationale available).")
            }
            else -> {
                updateUi("Camera permission is DENIED (no rationale or 'Don't ask again').")
            }
        }
    }

    private fun checkAndRequestCameraPermission() {
        when {
            // 3. Check if permission is already granted
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
                    PackageManager.PERMISSION_GRANTED -> {
                updateUi("Camera permission already granted. Proceeding...")
                // Perform camera operation
            }

            // 4. Show rationale if needed (user denied once, but not 'Don't ask again')
            shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA) -> {
                showRationaleDialog()
            }

            // Permission is denied and 'Don't ask again' was checked or never asked before
            else -> {
                // Request the permission directly or show initial explanation
                requestCameraPermissionLauncher.launch(android.Manifest.permission.CAMERA)
            }
        }
    }

    private fun showRationaleDialog() {
        AlertDialog.Builder(this)
            .setTitle("Camera Access Required")
            .setMessage("This app needs camera access to take photos. Please grant the permission.")
            .setPositiveButton("OK") { _, _ ->
                // Request permission again after user acknowledges rationale
                requestCameraPermissionLauncher.launch(android.Manifest.permission.CAMERA)
            }
            .setNegativeButton("No, thanks") { dialog, _ ->
                dialog.dismiss()
                updateUi("Camera permission denied. Feature might be limited.")
            }
            .show()
    }

    private fun handlePermissionDenied() {
        updateUi("Camera permission was denied.")

        // This is crucial: check if rationale is NOT shown, meaning 'Don't ask again' was checked
        if (!shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) {
            showSettingsDialog()
        } else {
            // User just denied the first time, or declined rationale. No further action needed yet.
            // The system will show rationale next time if requested.
        }
    }

    // 6. Guiding users to app settings
    private fun showSettingsDialog() {
        AlertDialog.Builder(this)
            .setTitle("Permission Denied Permanently")
            .setMessage("It looks like you've permanently denied camera permission. Please enable it in app settings to use this feature.")
            .setPositiveButton("Go to Settings") { _, _ ->
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.fromParts("package", packageName, null)
                }
                startActivity(intent)
            }
            .setNegativeButton("Cancel") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    override fun onResume() {
        super.onResume()
        // Refresh permission status when returning from settings or other screens
        updatePermissionStatus()
    }
}
XML
<!-- activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@id/statusTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Permission Status: Unknown"
        android:textSize="18sp"
        android:paddingBottom="24dp"/>

    <Button
        android:id="@id/requestPermissionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Request Camera Permission"/>

</LinearLayout>

Step 3: Check Permission Status

Always check if you already have the permission before requesting it. Use ContextCompat.checkSelfPermission for this. This prevents unnecessary permission dialogs and ensures your app can proceed immediately if access is already granted.

Step 4: Request Permission with Rationale

This is where many guides fall short. If shouldShowRequestPermissionRationale() returns true, it means the user previously denied the permission but did not check "Don't ask again". This is your opportunity to educate the user. Show an AlertDialog explaining why your app needs the permission. Only after they acknowledge your explanation should you launch the permission request using requestCameraPermissionLauncher.launch().

Step 5: Handle Permission Results

The callback lambda passed to registerForActivityResult is where you receive the result. isGranted tells you if the permission was given. If isGranted is false, call handlePermissionDenied() to perform further checks.

Step 6: Guiding Users to Settings for "Don't Ask Again"

⚠️ Common mistake: Many developers forget to handle the "Don't ask again" state. If shouldShowRequestPermissionRationale() returns false after the permission has been denied, it means one of two things:

  1. The user has never been asked for this permission before.
  2. The user has denied the permission and selected "Don't ask again".

In our handlePermissionDenied() method, if the permission was denied and shouldShowRequestPermissionRationale() is false, it strongly implies the user checked "Don't ask again". In this scenario, the system will no longer show the permission dialog for your app. Your only recourse is to direct the user to your app's settings screen where they can manually enable the permission. The showSettingsDialog() function demonstrates how to construct an Intent that opens your app's specific settings page.

Remember to call updatePermissionStatus() in onResume() to refresh the UI when the user returns from settings, as the permission state might have changed.

Limitations and Trade-offs

While this pattern covers most dangerous permissions effectively, keep these points in mind:

  • Background Location/All Files Access: Permissions like ACCESS_BACKGROUND_LOCATION or MANAGE_EXTERNAL_STORAGE have additional, more stringent requirements and dedicated flows (e.g., needing to describe usage in your Play Console listing, specific intents for all files access). This general pattern is not sufficient for them.
  • Over-requesting: Only request permissions when they are strictly necessary for a feature the user intends to use. Asking for all permissions upfront can lead to higher denial rates and a poor user experience.
  • Batch Permissions: Requesting multiple permissions at once (ActivityResultContracts.RequestMultiplePermissions) is possible, but handling the rationale for individual denials within a batch can become complex. Consider if a sequential request for critical permissions is more user-friendly.
  • User Frustration: While guiding to settings is necessary, it can still be frustrating for users. Design your explanations to be clear, concise, and justify the necessity of the permission.

Summary

Implementing a robust permission request flow is crucial for modern Android apps. By following this tutorial, you've learned to:

  • Utilize the ActivityResult API for simplified permission requests in Android 14.
  • Employ shouldShowRequestPermissionRationale() to provide crucial context to users who have previously denied a permission.
  • Handle persistent denials by directing users to app settings, preventing dead-end user experiences.
  • Maintain UI synchronization by updating permission status upon activity resume.

This approach ensures a user-friendly and functional experience, respecting user privacy while maintaining app functionality.

Advertisement