How to Request Permissions in Jetpack Compose

Pandiyan Mani
1 min readMay 13, 2024

--

We will work with the Accompanist Permissions library from Google.

implementation ("com.google.accompanist:accompanist-permissions:0.31.1-alpha")

Step 1: Add Required Permissions to Manifest

First, ensure that you have declared the necessary permissions in your AndroidManifest.xml file. For example, if your app requires access to the device’s camera, you should add the following line to your manifest:

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

Step 2: Check Permission Status

In your Jetpack Compose composable, you can use the rememberPermissionState function to check the status of the required permission. This function returns a PermissionState object that contains information about the permission status (granted, denied, or not requested yet).

package com.bharath.roomguide


import androidx.compose.runtime.Composable
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberPermissionState

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CheckCameraPermission() {
val cameraPermissionState = rememberPermissionState(android.Manifest.permission.CAMERA)
}

Step 3: Request Permission

Next, you can use the LaunchedEffect composable along with the permissionState to request the required permission when necessary. If the permission has not been granted yet, the permission request dialog will be shown to the user.

package com.bharath.roomguide


import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CheckCameraPermission() {
val cameraPermissionState = rememberPermissionState(android.Manifest.permission.CAMERA)
val requestLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
// Permission granted
} else {
// Handle permission denial
}
}

LaunchedEffect(cameraPermissionState) {
if (!cameraPermissionState.status.isGranted && cameraPermissionState.status.shouldShowRationale) {
// Show rationale if needed
} else {
requestLauncher.launch(android.Manifest.permission.CAMERA)
}
}
}

--

--