用Android7.0测试拍照的时候,出现异常android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()
是因为从Android N开始,要在应用间共享文件,需要发送一项 content://URI,并授予 URI 临时访问权限。
Android提供FileProvider来简单实现
实现方法:
1.在manifest中添加provider
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<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/mis_provider_paths"/>
</provider>
</application>
</manifest>
2.在res目录下新建一个xml文件夹,并且新建一个mis_provider_paths的xml文件
Paste_Image.png<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="camera_photos" path="."/>
</paths>
上面代表可以用外部存储的任意位置
如果只想在picture文件夹下读写
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="camera_photos" path="picture"/>
</paths>
3.代码中调用相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
uri = Uri.fromFile(file);
} else {
uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", file);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, code);
网友评论