其中大多数答案仅在不发送附件的情况下才适用。就我而言,有时我需要发送附件(ACTION_SEND)或两个附件(ACTION_SEND_MULTIPLE)。
因此,我从该线程中采用了最佳方法,并将它们组合在一起。它使用的是支持库,ShareCompat.IntentBuilder
但我只显示与ACTION_SENDTO和“ mailto:” uri匹配的应用。这样,我仅获得具有附件支持的电子邮件应用程序列表:
fun Activity.sendEmail(recipients: List<String>, subject: String, file: Uri, text: String? = null, secondFile: Uri? = null) {
val originalIntent = createEmailShareIntent(recipients, subject, file, text, secondFile)
val emailFilterIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
val originalIntentResults = packageManager.queryIntentActivities(originalIntent, 0)
val emailFilterIntentResults = packageManager.queryIntentActivities(emailFilterIntent, 0)
val targetedIntents = originalIntentResults
.filter { originalResult -> emailFilterIntentResults.any { originalResult.activityInfo.packageName == it.activityInfo.packageName } }
.map {
createEmailShareIntent(recipients, subject, file, text, secondFile).apply { `package` = it.activityInfo.packageName }
}
.toMutableList()
val finalIntent = Intent.createChooser(targetedIntents.removeAt(0), R.string.choose_email_app.toText())
finalIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedIntents.toTypedArray())
startActivity(finalIntent)
}
private fun Activity.createEmailShareIntent(recipients: List<String>, subject: String, file: Uri, text: String? = null, secondFile: Uri? = null): Intent {
val builder = ShareCompat.IntentBuilder.from(this)
.setType("message/rfc822")
.setEmailTo(recipients.toTypedArray())
.setStream(file)
.setSubject(subject)
if (secondFile != null) {
builder.addStream(secondFile)
}
if (text != null) {
builder.setText(text)
}
return builder.intent
}