Ahmet B.
Ahmet B.

Reputation: 1684

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?

Upvotes: 2

Views: 2329

Answers (2)

Christopher Pickslay
Christopher Pickslay

Reputation: 17772

CreateDocument() is now deprecated in favor of a constructor that takes the mime type as an argument. Here's how you should do what you're trying, where suggestedFileName is the name of the new file that will be pre-populated. The user can change the name of the file while creating it. The actual saved file path will be returned in the activity result (actualFileUri in my example):

val createFileLauncher = 
    registerForActivityResult(ActivityResultContracts.CreateDocument("audio/*")) { actualFileUri ->
    // do something with file URI
}

fun saveFile(suggestedFileName: String) {
    createFileLauncher.launch(suggestedFileName)
}

One thing to note--make sure your ActivityResultLauncher is a member variable and not a local variable in the saveFile function. Otherwise it may go out of scope and be garbage collected, and the intent will never be launched.

Upvotes: 2

S-Sh
S-Sh

Reputation: 3913

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
 }

Upvotes: 3

Related Questions