androidkotlinandroid-permissionsandroid-contentresolverandroid-securityexception

No persistable permission grants found for UID and Uri


I'm building an app that:

when I try to pick the second, I click the image and get the error:

No persistable permission grants found for UID "number" and Uri content://media/...

This is my code for picking the image:

val singlePhotoPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()){ imageUri ->
            if (imageUri != null){
                val contentResolver = context.contentResolver
                val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION

                try {
                    contentResolver.takePersistableUriPermission(imageUri, takeFlags)
                    viewModel.onEvent(AddPlantEvents.AddImageUri(imageUri))
                } catch (e: SecurityException) {
                    // Handle the SecurityException, e.g., show an error message
                    Log.e("PickVisualMedia", "Failed to take persistable permission", e)
                }
            }
    }

this is my button:

Button(
    modifier = Modifier
        .width(100.dp)
        .height(100.dp),
    onClick = {
        singlePhotoPickerLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }) {
    Text(
        text = "Add Photo",
        textAlign = TextAlign.Center,
        fontSize = 19.sp)
}

at first I didn't add ContentResolver and got a different error, then I searched and asked, and found out I need it to get a persistent URI. When I edited my code and launched the app to test it, I got the error as mentioned above, No persistable permission grants found for UID and URI

I did not find an answer using the same method I used to get the images, so I'm asking now to find a solution, or if I need to change the way I get images.

P.S.: I found out why I did not get a persistent URI: I removed this flag:

or Intent.FLAG_GRANT_WRITE_URI_PERMISSION

and the code works


Solution

  • The only contract that is (almost) guaranteed to offer a persistable permission grant is OpenDocument. PickVisualMedia may fall back to OpenDocument on some devices, but on those where it does not, you are not guaranteed to get a persistable permission grant.

    Your options are:

    1. Switch to OpenDocument, or

    2. Stick with PickVisualMedia, but deal gracefully when your takePersistableUriPermission() fails