3

我正在尝试使用拍照Intent(MediaStore.ACTION_IMAGE_CAPTURE)并将其保存到外部缓存中。在开始活动之前,我要求获得CAMERA, READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE权限。创建的代码示例Intent如下:

private Intent createIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Uri resultUri = null;
    File path = context.getExternalCacheDir();
    if (path != null && !path.exists() && !path.mkdirs()){
          return null;
    }
    File file = new File(path.getPath(), "resultImage.jpeg");
    if (path != null) {
       resultUri = FileProvider.getUriForFile(
       context,
       context.getPackageName() + ".provider",
       file);
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    return intent;
}

在运行 Android 10 及更低版本的设备上,它可以正常工作,但在 Android 11 上,我收到此错误并收到RESULT_CANCELED或只是在相机应用程序中崩溃。

FATAL EXCEPTION: main
    Process: com.google.android.GoogleCamera, PID: 19689
    java.lang.RuntimeException: java.lang.IllegalStateException: GCA not granted write permission to content://com.example.debug.provider/external_cache/resultImage.jpeg, the specified output in intent: Intent { act=android.media.action.IMAGE_CAPTURE flg=0x2 cmp=com.google.android.GoogleCamera/com.android.camera.activity.CaptureActivity (has extras) }.
        at mtt.run(PG:1)
        at bph.run(Unknown Source:68)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.IllegalStateException: GCA not granted write permission to content://com.example.debug.provider/external_cache/resultImage.jpeg, the specified output in intent: Intent { act=android.media.action.IMAGE_CAPTURE flg=0x2 cmp=com.google.android.GoogleCamera/com.android.camera.activity.CaptureActivity (has extras) }.

我的文件提供者:

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

和提供者路径:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
    <cache-path name="cache" path="/"/>
    <external-cache-path name="external_cache" path="/"/>
</paths>

我也尝试使用getExternalFilesDir而不是缓存,但得到了同样的错误。

4

0 回答 0