android - Android:通过意图发送电子邮件,文件作为附件
问题描述
关于这个主题有很多帖子,但我找不到我的问题的解决方案...
以下:我想通过电子邮件附件从我的应用程序中发送一个文件。
通过 Whatsapp 发送文件,保存到 Google Drive,...有效,但不适用于 K-9 Mail 或 Gmail(显示“无法附加文件”Toast 消息)。
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
intentShareFile.setType("application/zip");
intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("/sdcard/Download/ExportFile.zip"));
//intentShareFile.putExtra(Intent.EXTRA_TEXT, "message");
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intentShareFile.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(Intent.createChooser(intentShareFile, "Share File"));
我不明白为什么它适用于所有应用程序,除了电子邮件应用程序。
谁能帮我吗?
提前致谢。
解决方案
Amr EIZawawy 是对的。我需要创建文件的 Uri 并使用 File Provider API。
我不知道我是否做得太多,但这是我的解决方案:
- 在“res”目录(布局目录的兄弟)中的目录“xml”(首先创建)中创建一个名为“file_paths.xml”的文件。
该文件需要包含您要共享的文件的路径。对于外部下载目录,这是:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="download" path="Download/"/>
</paths>
// The internal path you'd be <files-path name.../> see [FileProvider][1] for all possibilities
- 在 AndroidManifest.xml 中定义 File 提供程序,其中包含指向刚刚创建的 XML 文件的元数据链接:
<application
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.<your-app-package-name>.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" /> // Link to the above created file
</provider>
...
- 实现代码:
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
intentShareFile.setType("application/zip");
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File newFile = new File(fileDirectory, "ExportFile.zip");
String authority = "com.bennoss.myergometertrainer.fileprovider"; // Must be the same as in AndroidManifest.
Uri contentUri = FileProvider.getUriForFile(getContext(), authority, newFile);
intentShareFile.putExtra(Intent.EXTRA_STREAM, contentUri);
//intentShareFile.putExtra(Intent.EXTRA_TEXT, "xxx");
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intentShareFile, "Share File"));
有关详细信息,请参阅:文件提供程序
推荐阅读
- python - 如何打印包含列名的数据框的每一行?
- java - 启动 TAP/TUN Openvpn3 时不允许操作
- javascript - 如何使用 w/Reactjs 从 MySQL 中删除数据?
- javascript - Mat-select 宽度的广义解
- oracle - 高级审计表和访问控制和数据导出
- python-3.x - 通过 Webhooks 和 PubSubHubbub (Python3) 的 YouTube 推送通知在订阅时返回 200,但在视频上传时没有
- swift - 带有条件泛型的 Swift 泛型类和扩展
- resize - tf.keras.layers.experimental.preprocessing.Resizing 的替代方案,适用于嵌入式系统 (ARM6)
- node.js - 从子集合中搜索包含来自父子集合的关键字
- java - 我尝试使用 ASM 将 Activity 的类名替换为 SimpleRemapper,但在 proguard apk 中找不到该类