This is a simple collection of sharing intents. There’s a more complete sample here with more advanced options that require the Twitter / Facebook APIs.
For all the Intent
s returned by the snippets below, check if they are launchable using these lines before launching the Intent. Intents can be ‘unlaunchable’ if, e.g. the targeted app is not installed. Even standard apps like the Messages app or phone dialer are usually not available on tablets.
val manager = context.getPackageManager()
val infos = manager.queryIntentActivities(intent, 0)
if (infos.size > 0) {
// intent can be launched
startActivity(context, intent)
}
The most basic sharing example
Sends a bit of text to any app.
val sendIntent = Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
type = "text/plain"
}
startActivity(Intent.createChooser(sendIntent, "Title"))
fun createShareEmail(fileUri: Uri?, mimeType: String? = null): Intent {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "message/rfc822"
if (fileUri != null) {
putExtra(Intent.EXTRA_STREAM, fileUri)
}
}
return intent
}
SMS/MMS
fun createShareSms(activity: AppCompatActivity, fileUri: Uri?, mimeType: String? = null): Intent {
val intent: Intent
if (Build.VERSION.SDK_INT >= 19) {
val p = Telephony.Sms.getDefaultSmsPackage(activity)
intent = createShareIntentForPackage(activity, fileUri, p)
} else {
intent = Intent(Intent.ACTION_VIEW, Uri.parse("smsto:"))
}
intent.apply {
// Optional additional fields:
// putExtra("sms_body", "")
// putExtra("address", "")
if (fileUri != null) {
putExtra(Intent.EXTRA_STREAM, fileUri)
type = mimeType ?: MIME_TYPE_IMAGE
}
}
return intent
}
Only useful for simple text. Check the complete example for sharing links to photos or videos, or uploading media.
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
setComponent(new ComponentName("com.facebook.katana",
"com.facebook.katana.activity.composer.ImplicitShareIntentHandler"))
putExtra("com.facebook.platform.extra.APPLICATION_ID", BuildConfig.APPLICATION_ID)
putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject.")
putExtra(android.content.Intent.EXTRA_TEXT, "This is my text to send.")
}
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
setPackage("com.twitter.android")
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
}
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
// If you prefer to share directly to WhatsApp and bypass the system picker,
// you can do so by using setPackage in your intent:
setPackage("com.whatsapp")
}