The Android photo picker library does not open the gallery on Android 11 and 12

891 Views Asked by At

I have implemented the Android photo picker library as described in the documentation, but on Android devices running Android 11 and 12 (API 30 and 31), the library automatically invokes the ACTION_OPEN_DOCUMENT intent action rather than the gallery.

The code:

private lateinit var pickMultipleMediaLauncher: ActivityResultLauncher<PickVisualMediaRequest>

Registers the photo picker activity launcher in multi-select mode.

private fun registerPhotoPicker() {
        pickMultipleMediaLauncher =
            registerForActivityResult(PickMultipleVisualMedia(imageSelectionLimitCount)) { uris ->
                uris.forEach {
                        getRealPathFromMediaURI(it)?.let { imagePath -> imagesPath.add(imagePath) }
                }
            }
    }

Launch the photo picker

pickMultipleMediaLauncher.launch(PickVisualMediaRequest.Builder().build())

Get the real path from media URI

fun getRealPathFromMediaURI(uri: Uri): String? {
        val projection = arrayOf(MediaStore.MediaColumns.DATA)
        val cursor = context.contentResolver.query(uri, projection, null, null, null)
        val columnIndex = cursor?.getColumnIndex(MediaStore.MediaColumns.DATA)

        return try {
            if (cursor != null) {
                cursor.moveToFirst()
                val filePath = columnIndex?.let { cursor.getString(it) }
                cursor.close()
                filePath
            } else null
        } catch (exception: Exception) {
            null
        }
    }
1

There are 1 best solutions below

0
On

Following the documentation, from this section, you can find a small paragraph explaining when and why the Intent ACTION_OPEN_DOCUMENT is automatically called.

If the photo picker isn't available on a device, the library automatically invokes the ACTION_OPEN_DOCUMENT intent action instead. This intent is supported on devices that run Android 4.4 (API level 19) or higher. You can verify whether the photo picker is available on a given device by calling isPhotoPickerAvailable().

Scrolling down the documentation to the section Device Availability will provide you a more detailed explanation and how to possibly solve your problem:

The photo picker is available on devices that meet the following criteria:

  • Run Android 11 (API level 30) or higher
  • Receive changes to Modular System Components through Google System Updates

Older devices that run Android 4.4 (API level 19) through Android 10 (API level 29) and Android Go devices running Android 11 or 12 that support Google Play services can install a backported version of the photo picker.