I'd like to share an image from my app and customize the caption based on the user's chosen app.
Below code works well, but the text is always the same, no matter which app the user chose.
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
putExtra(Intent.EXTRA_STREAM, uriToImage)
type = "image/png"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
How can I customize the text based on the chosen app?
You can customize the shared data, not only text, based on the user's chosen app by adding EXTRA_REPLACEMENT_EXTRAS to the Intent
created by Intent.createChooser()
.
This Intent
extra, is a Bundle
of apps package names to Bundle
s of the customized data you want to share, such as EXTRA_TEXT
, EXTRA_STREAM
, etc.
For example:
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "This is my text to send.") // Default text
putExtra(Intent.EXTRA_STREAM, uriToImage)
type = "image/png"
}
val shareIntent = Intent.createChooser(sendIntent, null)
shareIntent.putExtra( // Important to add the extra to the Chooser Intent, not `sendIntent`!
Intent.EXTRA_REPLACEMENT_EXTRAS, bundleOf(
"com.twitter.android" to bundleOf( // Twitter specific text
Intent.EXTRA_TEXT to "Hello Twitter!")
"another.app.com" to bundleOf( // Another app specific text
Intent.EXTRA_TEXT to "Hello another app!")
)
)
startActivity(shareIntent)
Note that for apps which we don't have a custom text, we still want to set EXTRA_TEXT
on the sendIntent
. Android will automatically pick the right data for the right app based on its package name.