I'm trying to take a photo using Intent(MediaStore.ACTION_IMAGE_CAPTURE)
and save it to the external cache. Before starting the Activity I ask for CAMERA
, READ_EXTERNAL_STORAGE
, WRITE_EXTERNAL_STORAGE
permissions.
The code example of the Intent
creation below:
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;
}
On devices running with Android 10 and lower it works fine but on Android 11 I'm getting this error and receive RESULT_CANCELED
or just crash in the Camera app.
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) }.
My File Provider:
<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>
and provider path's:
<?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>
I also tried to use getExternalFilesDir
instead of cache but got the same error.