解决方法:
1.
在AndroidManifest.xml中添加如下代码
<!--解决在安卓7.0以上调用相机拍照出现android.os.FileUriExposedException 问题--> <!-- 注意: authorities:app的包名.fileProvider grantUriPermissions:必须是true,表示授予 URI 临时访问权限 exported:必须是false resource:中的@xml/file_paths是我们接下来要添加的文件 --> <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.
在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件,里面内容如下
path:需要临时授权访问的路径(.代表所有路径)
name:就是你给这个访问路径起个名字
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path path="." name="external_storage_root" /> </paths>
3.在需要打开相机时进行判断
//获取权限,打开照相机 private void openCamera() { Uri imageUri; //创建File对象,用于存储拍摄的照片 File outputImage = new File(getPhotoPath()); try { if (outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ imageUri = FileProvider.getUriForFile(UserImageUpdateActivity.this,"app包名.fileprovider",outputImage); }else { imageUri = Uri.fromFile(outputImage); } //启动相机 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, REQUEST_CODE_FROM_CAMEIA); }// 拍照路径 public String getPhotoPath() { File file = new File(Constant.HEAD_PORTRAIT); if (!file.exists()) { file.mkdirs(); } String path = file.getAbsolutePath() + "/userphoto.jpg"; return path; }
判断sdk版本,如果大于24,则使用provider,低于则使用应用关联缓存目录存下图片。