我希望实现一个按钮,按下它会打开带有附件文件的默认电子邮件客户端。
我关注 this ,但是在 startActivity 上收到一条错误消息,说它在我给它一个 Intent 时期待一个 Activity 参数。 我正在使用 API 21 和 Android Studio 1.1.0,所以也许它与链接中提供的答案中的评论有关?
这是我作为 Android 开发人员的第四天,如果我遗漏了一些非常基本的东西,非常抱歉。
这是我的代码:
public void sendFileToEmail(File f){
String subject = "Lap times";
ArrayList<Uri> attachments = new ArrayList<Uri>();
attachments.add(Uri.fromFile(f));
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
最佳答案
带有 Kotlin fragment 的官方文档在这里:https://developer.android.com/guide/components/intents-common#ComposeEmail
我认为你的问题是你没有使用正确的文件路径。
以下对我有用:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "temp/attachement.xml";
File file = new File(root, pathToMyAttachedFile);
if (!file.exists() || !file.canRead()) {
return;
}
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
编辑:请求存储访问权限只是为了共享您的应用专用的文件可能不是一个好主意。幸运的是,经过一些配置,从您的应用程序私有(private)存储中共享文件非常容易。请参阅本指南:https://developer.android.com/training/secure-file-sharing/setup-sharing
如果您共享外部存储上的文件,您还需要通过如下 list 文件授予用户权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
关于android - 在 Android 上以编程方式发送带有附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28809776/