首页 > 解决方案 > 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"));

我不明白为什么它适用于所有应用程序,除了电子邮件应用程序。
谁能帮我吗?
提前致谢。

标签: androidandroid-intent

解决方案


Amr EIZawawy 是对的。我需要创建文件的 Uri 并使用 File Provider API。
我不知道我是否做得太多,但这是我的解决方案:

  1. 在“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

  1. 在 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>
    ...
  1. 实现代码:
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"));

有关详细信息,请参阅:文件提供程序


推荐阅读