Save picture in app-reserved memory in Android 11

603 Views Asked by At

Android 11 makes scoped storage mandatory. In this scenario, I would like my app to take a picture and save it into some kind of app-reserved memory so that the picture is still available when deleted from the gallery. I am using the following approach

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(newFile);
if (android.os.Build.VERSION.SDK_INT >= 24) {
   outputFileUri = FileProvider.getUriForFile(myActivity, BuildConfig.APPLICATION_ID + ".provider", newFile);
   cameraIntent.setFlags(FLAG_GRANT_READ_URI_PERMISSION);
   cameraIntent.setFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

The problem boils down to how do I create newFile in the above snippet since getExternalStoragePublicDirectory() is no longer usable due to scoped storage. I have read through the documentation and various posts, but the matter appears to be broad and vague. Please avoid posting a bare link to the MediaStore API.

1

There are 1 best solutions below

3
On

You can use SAF (Storage Access Framwork) instead.

Create A File using SAF:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_TITLE, "myImage.jpg");

startActivityForResult(intent, your-request-code);

Then grab the uri in onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == your-request-code && resultCode == Activity.RESULT_OK && data != null) {
        Uri uri = data.getData(); //Do stuff...
    }
}

Reference: Access documents and other files from shared storage