Search code examples
androidphoto-picker

How to multi select MIME type for Android PhotoPicker


I'd like to use Android PhotoPicker, then I want multi MIME type that can JPEG, PNG but can only single MIME type, how can I get it?

// Launch the photo picker and let the user choose only images/videos of a
// specific MIME type, such as GIFs.
val mimeType = "image/gif"
pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.SingleMimeType(mimeType)))

https://developer.android.com/training/data-storage/shared/photopicker


Solution

  • You can create a subclass of PickVisualMedia as follows:

    class PickImage : PickVisualMedia() {
        override fun createIntent(context: Context, input: PickVisualMediaRequest): Intent {
            val intent = super.createIntent(context, input)
            intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/jpeg", "image/png"))
            return intent
        }
    }
    
    interface Launcher {
        fun launch()
    }
    
    @Composable
    fun rememberPickImageLauncherForActivityResult(onResult: (Uri?) -> Unit): Launcher {
        val launcher = rememberLauncherForActivityResult(contract = PickImage(), onResult = onResult)
        return object : Launcher {
            override fun launch() {
                launcher.launch(PickVisualMediaRequest(PickVisualMedia.SingleMimeType("*/*")))
            }
        }
    }
    
    val launcher = rememberPickImageLauncherForActivityResult { uri ->
      // read data from the uri
    }
    
    launcher.launch()
    

    According to the following document, when using EXTRA_MIME_TYPES, the MIME type should be set to "/". That's the reason for setting SingleMimeType to "/".

    https://developer.android.com/guide/components/intents-common

    EXTRA_MIME_TYPES

    An array of MIME types corresponding to the types of files your app is requesting. When you use this extra, you must set the primary MIME type in setType() to "/".