自Android 7.0以上系统版本,如果应用A本身文件提供给其它应用B使用时,如果应用B没有该文件的读写权限,就会抛出FileUriExposedException。例如APP保存一张图片,通过Intent启动把图片的URI传递给系统图片查看软件,就会出现异常。谷歌推荐解决方式通过FileProvider的方式。具体如下:
(1)在清单文件<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>
(2)配置file_paths.xml文件,如下是示例代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
name="test"
path="" />
</paths>
</resources>
其中<paths>中对应4中标签分别对应的目录如下:
files-path —Context.getFilesDir()
cache-path — Context.getCacheDir()
external-path — Environment.getExternalStorageDirectory()
external-files-path— Context.getExternalFilesDir()
external-cache-path— Context.getExternalCacheDir()
(3)FileProvider在java中的使用
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context,
"app的包名.fileprovider",file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(tempFile);
}
addUiIntentFlags(intent);
intent.setDataAndType(uri, mimeType);
startActivity(intent);