Search code examples
androidkotlinandroid-intent

Intent.createChooser doesn't show image or file name


I'm using the code below to allow a user to share an image with another app:

val intent: Intent = Intent().apply {
    type = "image/jpeg"
    if (uris.size == 1) {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_STREAM, uris.first())
    } else {
        action = Intent.ACTION_SEND_MULTIPLE
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
        putExtra(Intent.EXTRA_MIME_TYPES, arrayOf(extraMimeTypes))
    }
}
val shareIntent = Intent.createChooser(intent, null)
startActivity(shareIntent)

Everything works functionally (i.e. I'm able to share the image via messages or email) except that there is no image or file name shown in the share sheet:

enter image description here

But I would like it to look something like this:

enter image description here

What do I need to do to show the image in the share sheet?


Solution

  • For ACTION_SEND, you need to add ClipData, which is what is used to populate that preview:

    val intent = Intent(Intent.ACTION_SEND).apply {
      clipData = ClipData.newRawUri(null, uri)
      putExtra(Intent.EXTRA_STREAM, uri)
      type = "image/jpeg"
      addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    
    startActivity(Intent.createChooser(intent, null))
    

    The reason is that the framework copies the ClipData out of the ACTION_SEND and puts it in the ACTION_CHOOSER Intent created by createChooser(). It does not copy any EXTRA_STREAM value, though.

    Alternatively, you could use ShareCompat.IntentBuilder, which does all that for you:

    ShareCompat.IntentBuilder.from(this)
      .setType("image/jpeg")
      .addStream(uri)
      .startChooser()
    

    See this blog post of mine for more.