我想通过gmail或其他其他电子邮件应用程序发送存储在应用程序内部缓存中的文本文件。我添加了FileProvider,以一次性权限访问该文件。
当我在带有Android 5.0的设备上运行应用程序时,它可以正常工作。当我在6.0的设备上运行它时,它会失败。一个故障是一个例外:
没有发现要处理意图的活动{act = android.intent.action.send flg = 0x3 clip = {null t:附加日志文件。}(extras)}
当我省略 intent.setDataAndType (uri, "text/plain")
。
另一个失败,如果我确实包括上述语句,则是Gmail的错误。它显示了带有图形的附件文件名,使我相信它可以正确访问它。它还在"到"行中显示了附件的路径 - 本质上是URI,但缺少"文件:"前缀。如果我尝试发送消息,它会给我一个错误消息:"地址无效。"如果我从"到"行中删除此虚假地址,我可以成功发送消息,并使用附件发送。
换句话说,我对FileProvider的使用,包括各种"设置"文件,似乎都在起作用。我显然在意图的用法中有问题,一个地方。这是我的代码 - 带有伪造的" to"地址的后一个版本。
清单:
<application
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp.file_access"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
filepaths.xml(在res/xml目录中):
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path path="./" name="files" />
</paths>
创建意图的代码:
public static void sendFile (Context context, String path)
{
File file = new File (path);
Uri uri = FileProvider.getUriForFile (context, "com.myapp.file_access", file);
Intent intent = new Intent (Intent.ACTION_SEND);
intent.putExtra (Intent.EXTRA_EMAIL, new String[] {"you@gmail.com"});
intent.putExtra (Intent.EXTRA_SUBJECT, "your file");
intent.putExtra (Intent.EXTRA_STREAM, uri);
intent.putExtra (Intent.EXTRA_TEXT, "file attached.");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType (uri, "text/plain");
context.startActivity (intent);
}
不确定9个月后是否仍然可用。
- 数据类型应为"消息/RFC822"
- gmail的附件仅在文件在外部存储" mnt/card/{your_file_path}"上时,对于任何其他文件路径