android手机拍照功能遇到的坑(FileUriExposedException)

android调取相册崩溃异常:
android.os.FileUriExposedException: file:///storage/emulated/0/1526016747317photo.jpg exposed beyond app through ClipData.Item.getUri();
原因:
android 7.0版本以前
//加载路径
Uri uri = Uri.fromFile(new File(mFilePath));
file文件直接转成url
android 7.0 以后
Android不再允许在app中把file文件直接转成url
解决办法:
/**
 * 打开相机拍照
 */
private String mFilePath = Environment.getExternalStorageDirectory().getPath() + "/" +
        String.valueOf(System.currentTimeMillis()) + "photo.jpg";
private void openCamera() {
       Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      //加载路径
       if(android.os.Build.VERSION.SDK_INT<24){
       Uri uri = Uri.fromFile(new File(mFilePath));
       }else {
       ContentValues contentValues = new ContentValues(1);
       contentValues.put(MediaStore.Images.Media.DATA, mFilePath);
       Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);}
      //指定存储路径,保存原图 
      openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 
      startActivityForResult(openCameraIntent, 6);
}
或者在Application 中加入
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();


猜你喜欢

转载自blog.csdn.net/mt11111111/article/details/80280193