欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-02-13 19:42:22
...

代码的改写方法

   /**
    * 老方法[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<ResolveInfo> 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注册

<application
    ...
    <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.harry.shopping.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    ...
</application>

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

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

<?xml version="1.0" encoding="utf-8"?>
<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。


相关标签: Android