在开发读取本地图片的功能时,使用了Uri.fromFile(path); 在7.0以下版本是没有问题的,但是在7.0及以上版本则会报出FileUriExposedException,这是Google为了安全考虑,做出的调整,同时也给出了对应的解决办法。
办法一:使用FileProvider
在清单文件中的application节点下添加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="xxx.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
其中xxx最好用包名来标识,在file_paths.xml中编写该Provider对外提供文件的目录。
使用时:打开照相机
File file = new File(path);
// 第二个参数是manifest中定义的`authorities`
Uri uri = FileProvider.getUriForFile(context, "xxx.fileprovider", file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
...... 其他参数
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//给目标一个临时的授权。
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
办法二:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, TAKE_PHOTO_REQ_CODE);