Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Multiple Mime Types to ActivityResultLauncher.launch()

I have following code

val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
    //Some code here..
}

and somewhere else ,

getContent.launch("application/vnd.openxmlformats-officedocument.wordprocessingml.document")

I can successfully select the docx file . I need to select either pdf or doc or text or docx rather just to be able to select one kind(here docx).

like image 868
Nikki Avatar asked Mar 26 '21 08:03

Nikki


2 Answers

I would recommend using OpenDocument instead of GetContent.

val documentPick =
    registerForActivityResult(ActivityResultContracts.OpenDocument()) { result ->
        // do something 
    }

While launching the intent just add the mime types you want to get

documentPick.launch(
            arrayOf(
                "application/pdf",
                "application/msword",
                "application/ms-doc",
                "application/doc",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "text/plain"
            )
        )
like image 70
Hussain Avatar answered Oct 24 '22 07:10

Hussain


Using array doesn't work in my case. Instead, the following worked correctly. Here custom class of ActivityResultContracts.GetContent is used. fun "createIntent" is overrided to customize method to make intent from the input.

    // custom class of GetContent: input string has multiple mime types divided by ";"
    // Here multiple mime type are divided and stored in array to pass to putExtra.
    // super.createIntent creates ordinary intent, then add the extra. 
    class GetContentWithMultiFilter:ActivityResultContracts.GetContent() {
        override fun createIntent(context:Context, input:String):Intent {
            val inputArray = input.split(";").toTypedArray()
            val myIntent = super.createIntent(context, "*/*")
            myIntent.putExtra(Intent.EXTRA_MIME_TYPES, inputArray)
            return myIntent
        }
    }

    // define ActivityResultLauncher to launch : using custom GetContent
    val getContent=registerForActivityResult(GetContentWithMultiFilter()){uri ->
    ... // do something
    }

    // launch it
    // multiple mime types are separated by ";".
    val inputString="audio/mpeg;audio/x-wav;audio/wav"
    getContent.launch(inputString)
like image 3
lglink Avatar answered Oct 24 '22 07:10

lglink