FileProvider的使用
在Android 7.0 以上的系统中,尝试传递 file://URI
会触发FileUriExposedException
解决办法
第一步 在AndroidManifest.xml中配置FileProvider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
第二步 在res下创建 xml 文件夹,并创建file_paths文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path
name="ext_sd_files"
path="." />
<files-path
name="int_files"
path="." />
<external-path
name="ext_files"
path="." />
<cache-path
name="cache_files"
path="." />
<external-files-path
name="ext_int_files"
path="." />
</paths>
- 对file_path中的目录描述
1: 内部存储空间应用私有目录下的 files/ 目录
<files-path name="name" path="path" /> 物理路径相当于Context.getFilesDir() + /path/
2: 内部存储空间应用私有目录下的 cache/ 目录
<cache-path name="name" path="path" /> 物理路径相当于Context.getCacheDir() + /path/
3: 外部存储空间根目录
<external-path name="name" path="path" /> 物理路径相当于Environment.getExternalStorageDirectory() + /path/
4: 外部存储空间应用私有目录下的 files/ 目录
<external-files-path name="name" path="path" /> 物理路径相当于Context.getExternalFilesDir(String) + /path/
5: 外部存储空间应用私有目录下的 cache/ 目录
<external-cache-path name="name" path="path" /> 物理路径相当于Context.getExternalCacheDir() + /path/
第三步 使用FileProvider API
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context,context.getApplicationContext().getPackageName()+".fileprovider", file);
} else {
uri = Uri.fromFile(file);
}