Search code examples
androidandroid-intentstartactivityforresultregisterforactivityresult

How to add intent type by using ActivityResultContracts.CreateDocument()


I was using the below code to create a file on external storage

        Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "audio/*"
        putExtra(Intent.EXTRA_TITLE, fileName)
    }.also {
        startActivityForResult(it, CREATE_FILE)
    }

Since startActivityForResult is deprecated I am using ActivityResultContracts.CreateDocument(). However I couldn't added intent type which is shown in the above code as type = "audio/*"

Here is my code;

       val createFileIntent =
        registerForActivityResult(ActivityResultContracts.CreateDocument()) { uri ->
            // todo
        }
      
       // usage
       createFileIntent.launch(fileName)

How can I add intent type?


Solution

  • According with documentation for ActivityResultContracts.CreateDocument , you can inherit the class to customize Intent, for example:

      class CreateSpecificTypeDocument(private val type: String) :
            ActivityResultContracts.CreateDocument() {
            override fun createIntent(context: Context, input: String): Intent {
                return super.createIntent(context, input).setType(type)
            }
        }
    

    and then register it for activity result:

     registerForActivityResult(CreateSpecificTypeDocument("audio/*")) {
      // todo
     }