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 I got this Error

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

This is my code Block 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 persist Uri, when I edited my code and launch the app to test it I got the error as mentioned above "No persistable permission grants found for UID and Uri"

I did not found an answer using the same method I use to get the Images so I'm asking now to find solution or If I need to change the way I get Images.

P.S: I found out why I did not get persist uri: I removed this flag:

or Intent.FLAG_GRANT_WRITE_URI_PERMISSION

and the 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