我想通過gmail或其他電子郵件應用程序發送存儲在應用程序內部緩存中的文本文件。我已經添加FileProvider來給予文件的一次權限訪問權限。使用FileProvider cache-path for gmail附件顯示「無效」錯誤
當我在Android 5.0設備上運行我的應用程序時,它可以正常工作。當我在6.0的設備上運行它時,它失敗了。一個故障是一個例外:
無活動處理意圖{行爲= android.intent.action.SEND FLG = 0x3剪輯= {NULL T:。登錄附加文件}(具有額外)}
發生這種情況時,我省略了intent.setDataAndType (uri, "text/plain")
。
另一個失敗,如果我包括上面的語句,是gmail的錯誤。它顯示附件文件的名稱和圖形,使我相信它正確訪問它。它還在「到」行中顯示了附件的路徑 - 基本上是uri,但缺少「file:」前綴。如果我嘗試發送郵件,它會給我一條錯誤消息:「地址無效。」如果我從「到」行刪除這個僞造的地址,我可以成功地發送消息和附件。
換句話說,我對FileProvider的使用,包括各種「設置」文件,似乎正在工作。我顯然有一些錯誤的地方,可能是Intent的用法。這是我的代碼 - 後者的版本與僞造的「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[] {"[email protected]"});
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);
}