In my application a user can open the gallery and select their images by using androidX method:
registeredIntent = registerForActivityResult(new ActivityResultContracts.GetMultipleContents(), this);
And the callback for the result is sent in this method:
@Override
public void onActivityResult(List<Uri> result) {
if(result != null && result.size() > 0) {
sliderImageAdapter.addItems(result);
binding.includeResultTask.imageSlider.setSliderAdapter(sliderImageAdapter, true);
}
}
So far this works pretty well, the images are shown in my gallery component by adding the Uris in my adapter, the problem is that I save those in my database and when I restart the application the permissions are revoked and my application crash. I tried by adding this in my callback for each item:
requireActivity().getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
But I get this error:
Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{41a7dce 26094:it.ilogreco.levelup/u0a482} (pid=26094, uid=10482) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
I have even tried to use this for each item:
context.grantUriPermission(context.getPackageName(), uri, FLAG_GRANT_READ_URI_PERMISSION);
but I get this error:
UID 10482 does not have permission to content://com.android.providers.media.documents/document/image:108953 [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
I load the Uris one time and save them to the database with the registerForActivityResult, I can't open the media gallery again with the API because it doesn't make sense, any idea how to get those permissions? I would like to avoid copying the content in the callback.
CodePudding user response:
Switch from ActivityResultContracts.GetMultipleContents
to ActivityResultContracts.OpenMultipleDocuments
. Then, your takePersistableUriPermission()
calls should work. You can only get persistable Uri
permissions on documents obtained via the Storage Access Framework, which is what OpenMultipleDocuments
uses.