【发布时间】:2016-09-02 16:00:24
【问题描述】:
Android N 现在似乎需要 FileProvider,所以我正在尝试实现 FileProvider 将文件从网络保存到本地临时位置,然后我需要读取这个临时文件。
我这样做是为了设置 FileProvider:
Manifest.xml:
</application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
然后我的res/xml 文件夹中有一个provider_paths.xml 文件,其中包含:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="Download" path="Download"/>
</paths>
最后,这是我必须创建临时文件的 java 代码:
try {
final File imagePath = new File(getContext().getFilesDir(), "Download");
final File newFile = new File(imagePath, filename + "." + filePrefix);
final Uri contentUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", newFile);
final File tempFile = new File(contentUri.getPath());
tempFile.getParentFile().mkdirs();
final FileWriter writer = new FileWriter(tempFile);
writer.flush();
writer.close();
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
final FileWriter writer = new FileWriter(tempFile);这一行抛出异常java.io.FileNotFoundException: /Download/TempFile.html (No such file or directory)
关于我做错了什么有什么建议吗?谢谢!
更新/编辑:
当前保存文件的方法将文件放置在此处:
/storage/emulated/0/Download/TempFile.html
这很好,直到我尝试使用 Intent 来使用它,如下所示:
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), fileType.getMimeType());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
然后抛出这个异常:
android.os.FileUriExposedException:file:///storage/emulated/0/Download/TempFile.html exposed beyond app through Intent.getData()
【问题讨论】:
标签: java android android-fileprovider