How to properly ask for COARSE and FINE location permission using accompanist?

31 Views Asked by At

Accompanist allows to ask for one permission at once is it possible to ask for these two location permission at once?

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

That's my code

PermissionUtils.requestForPermission(
    context = context,
    permission = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
        Manifest.permission.ACCESS_FINE_LOCATION
    } else {
        Manifest.permission.ACCESS_COARSE_LOCATION
    },
)
@Composable
fun rememberPermissionLauncher(
    onGranted: () -> Unit,
    onDenied: () -> Unit,
): PermissionLauncher {
    return PermissionLauncher(
        rememberLauncherForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                onGranted()
            } else {
                onDenied()
            }
        }
    )
}

class PermissionLauncher(
    val launcher: ManagedActivityResultLauncher<String, Boolean>
)
1

There are 1 best solutions below

1
Miroslav Hýbler On BEST ANSWER

Yes, it is possible, use RequestMultiplePermissions() instead of RequestPermission(). With this you can request multiple permissions at single time, and in callback you will get Map<String, Boolean> where permissions are keys and value is granted/denied Boolean.

@Composable
fun rememberPermissionLauncher(
    onGranted: () -> Unit,
    onDenied: () -> Unit,
): PermissionLauncher {
    return PermissionLauncher(
        rememberLauncherForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { map ->
            if (!map.containsValue(false)) {
                onGranted()
            } else {
                onDenied()
            }
        }
    )
}

class PermissionLauncher(
    val launcher: ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>>
)

I am using accompanist-permissions version 0.28.0.