参考官方解释 https://developer.android.com/reference/android/os/FileUriExposedException.html
解决办法 https://developer.android.com/reference/android/support/v4/content/FileProvider.html
大致处理步骤:
1. 在mainfest中加入FileProvider注册
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="App包名.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
...
</application>
</manifest>
2. 新建res/xml/file_paths.xml文件
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
<files-path name="my_docs" path="docs/"/>
</paths>
<paths> 中可以定义以下子节点
子节点 | 对应路径 | 示例 |
---|---|---|
files-path | Context.getFilesDir() | <files-path name="name" path="path" /> |
cache-path | Context.getCacheDir() | <cache-path name="name" path="path" /> |
external-path | Environment.getExternalStorageDirectory() | <external-path name="name" path="path" /> |
external-files-path | Context#getExternalFilesDir(String) Context.getExternalFilesDir(null) | <external-files-path name="name" path="path" /> |
external-cache-path | Context.getExternalCacheDir() | <external-cache-path name="name" path="path" /> |
3. 使用示例
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "App包名.fileprovider", newFile);
4. 遇到的问题
Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
原因:mainfest中 android:authorities 与 代码 FileProvider.getUriForFile(getContext(), "App包名.fileprovider", newFile);App包名.fileprovider
不一致