Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
上面的代码打开一个对话框,显示以下应用程序:-蓝牙,谷歌文档,雅虎邮件,Gmail, Orkut, Skype等。
实际上,我想过滤这些列表选项。我只想显示电子邮件相关的应用程序,如Gmail和雅虎邮件。怎么做呢?
我曾在Android Market应用中看到过这样的例子。
打开Android Market应用程序
打开任何开发者指定了他/她的电子邮件地址的应用程序。(如果你找不到这样的应用程序,请打开我的应用程序:- market://details?id=com.becomputer06.vehicle.diary.free,或通过“车辆日记”搜索)
向下滚动到“开发者”
点击“发送电子邮件”
对话框只显示电子邮件应用程序,如Gmail,雅虎邮件等。它不显示蓝牙,Orkut等。什么样的代码产生这样的对话?
这些答案大多只适用于不发送附件的简单情况。在我的情况下,我有时需要发送附件(ACTION_SEND)或两个附件(ACTION_SEND_MULTIPLE)。
所以我从这条线索中选择了最好的方法并将它们结合起来。它使用支持库的ShareCompat。但是我只展示了匹配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
}