Android7.0及以上拍照获取照片无法使用file://,使用content://URI

代码的改写方法

   /**
    * 老方法[Android7.0以及以上报错FileUriExposedException]
    */
private void doTakePhotoOld() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            File newFile = createTakePhotoFile();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    }

/**
  * 拍照新方法[全尺寸]
  */
private void doTakePhoto() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
            File newFile = createTakePhotoFile();
            Uri contentUri = FileProvider.getUriForFile(this, "com.harry.shopping.fileprovider", newFile);
            Log.i(TAG, "contentUri = " + contentUri.toString());
                        List resInfoList= getPackageManager().queryIntentActivities(takePhotoIntent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, contentUri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            startActivityForResult(takePhotoIntent, REQUEST_CAMERA);
        }
    }
/**
     * @return 拍照之后存储的文件
     */
    @NonNull
    private File createTakePhotoFile() {
        File imagePath = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "take_photo");
        if (!imagePath.exists()) {
            imagePath.mkdirs();
        }
        File file = new File(imagePath, "default_image.jpg");
        mCurrentPhotoPath = file.getPath();// 存储拍照的路径
        return file;
    }

对FileProvider进行设置

AndroidManifest.xml注册

...
    "android.support.v4.content.FileProvider"
            android:authorities="com.harry.shopping.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            "android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        
    ...

注意,android:authorities属性值和之前FileProvider.getUriForFile方法使用的authorities必须保持一致。

在res/xml新建file_paths.xml设置文件路径


<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="images" path="Android/data/com.harry.shopping/files/Pictures" />
paths>

经过以上操作就可以在onActivityResult里面获取到照片路径mCurrentPhotoPath。


你可能感兴趣的:(Android7.0及以上拍照获取照片无法使用file://,使用content://URI)