Fix java.lang.SecurityException for ACTION_OPEN_DOCUMENT

This commit is contained in:
Ritika Pahwa 2025-07-12 15:53:24 +05:30
parent 8fc7e1039b
commit ebd1c04420

View file

@ -256,7 +256,9 @@ object FilePicker : Constants {
*
*/
val intent = if (openDocumentIntentPreferred) {
Intent(Intent.ACTION_OPEN_DOCUMENT)
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
}
} else {
Intent(Intent.ACTION_GET_CONTENT)
}
@ -271,6 +273,7 @@ object FilePicker : Constants {
callbacks: Callbacks
) {
if (result.resultCode == Activity.RESULT_OK && !isPhoto(result.data)) {
takePersistableUriPermissions(activity, result)
try {
val files = getFilesFromGalleryPictures(result.data, activity)
callbacks.onImagesPicked(files, ImageSource.DOCUMENTS, restoreType(activity))
@ -283,6 +286,23 @@ object FilePicker : Constants {
}
}
/**
* takePersistableUriPermission is necessary to persist the URI permission as
* the permission granted by the system for read or write access on ACTION_OPEN_DOCUMENT
* lasts only until the user's device restarts.
* Ref: https://developer.android.com/training/data-storage/shared/documents-files#persist-permissions
*
* This helps fix the SecurityException reported in this issue:
* https://github.com/commons-app/apps-android-commons/issues/6357
*/
private fun takePersistableUriPermissions(context: Context, result: ActivityResult) {
result.data?.data?.also { uri ->
val takeFlags: Int = (Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
}
}
/**
* onPictureReturnedFromCustomSelector.
* Retrieve and forward the images to upload wizard through callback.