Android 7.0和8.0相机权限问题

java.lang.SecurityException: Permission Denial: writing android.support.v4.content.FileProvider uri content://com.example.user014.komodo.fileprovider/camera_photos/storage/emulated/0/crop_photo.jpg from pid=10041, uid=10022 requires the provider be exported, or grantUriPermission()

上面这个异常先不谈,先说说Android7.0以后调用相机会崩溃的问题

先说以前调用系统相机拍照的时候,流程是这样的:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

   if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

  //创建一个路径保存图片 photoFile = ImageUtil.createImageFile();

     if (photoFile != null) { photoURI = Uri.fromFile(photoFile);

    //传递一个Uri takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

    startActivityForResult(takePictureIntent, TAKE_PHOTO);

  }

}

但是在Android7.0系统下直接崩溃了,后来在网上找了原因,是由于Android7.0执行了“StrictMode API 政策禁”的原因,有兴趣的可以自己去搜索了解,我就不解释了,给大家一个地址去看,已经写的很详细了

https://www.jianshu.com/p/fbae13948115   文章后面还有GitHub 的demo地址

我要说的是,拍照和选择照片完成后,经过裁剪后的照片,需要有Uri的读写权限才可以使用,否则会出现无法获取的错误:

.//添加Uri读写权限

public static void cropImageUri(Activity activity, Uri orgUri, Uri desUri, int aspectX, int aspectY, int width, int height, int requestCode) {

       Intent intent = new Intent("com.android.camera.action.CROP");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            Log.d(TAG, "cropImageUri: " + "provider被授予权限导出");

           intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

       }

       intent.setDataAndType(orgUri, "image/*");

       intent.putExtra("crop", "true");

       intent.putExtra("aspectX", aspectX);

       intent.putExtra("aspectY", aspectY);

       intent.putExtra("outputX", width);

       intent.putExtra("outputY", height);

       intent.putExtra("scale", true);

       //将剪切的图片保存到目标Uri中

       intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);

       intent.putExtra("return-data", false);

       intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

       intent.putExtra("noFaceDetection", true);

        //添加Uri读写权限,否则7.0以上版本无法读写Uri路径文件 

       List resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

       for (ResolveInfo resolveInfo : resInfoList) {

            String packageName = resolveInfo.activityInfo.packageName;

            activity.grantUriPermission(packageName, desUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |    Intent.FLAG_GRANT_READ_URI_PERMISSION);

       }

      activity.startActivityForResult(intent, requestCode);

}

你可能感兴趣的:(Android 7.0和8.0相机权限问题)