My android application recently got rejected with this error, The change in this build is that I have used CameraX and created a custom camera , so post taking a picture/video, I want to write it a file and save the 'URI' so that I can upload this in background. Is there are safer/better way to save my image to user's file directory that is promoted by Google
How to solve : All Files Access Permission policy : Access to device storage not required error
426 Views Asked by Avinash Sharma At
2
There are 2 best solutions below
2
On
Check if your app can function without requiring all files access permission or not. Cause if you're using that permission for manipulating media files then you may not need it.
Try replacing it with SAF (Storage Access Framework) or Mediastore API. So you won't need the All files access permission at all.
According to your use case, if you want to save a media files in external storage then you can do it using mediastore easily.
You can save bitmap to storage and update the MediaStore like this,
public static Uri saveBitmap(Context context,
Bitmap bitmap,
Bitmap.CompressFormat compressFormat,
String mime_type,
String display_name,
String path) {
OutputStream openOutputStream;
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, display_name);
contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, mime_type);
contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, path);
ContentResolver contentResolver = context.getContentResolver();
Uri insert = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
if (insert != null) {
try {
openOutputStream = contentResolver.openOutputStream(insert);
if (openOutputStream == null) {
throw new IOException("Failed to open output stream.");
} else if (bitmap.compress(compressFormat, 90, openOutputStream)) {
openOutputStream.close();
return insert;
} else {
throw new IOException("Failed to save bitmap.");
}
} catch (IOException unused) {
contentResolver.delete(insert, null, null);
return insert;
} catch (Throwable th) {
th.addSuppressed(th);
}
}
return null;
}
In order to take and save media to the phone, you should not request any storage-related permissions. You can use MediaStore to achieve this: https://developer.android.com/training/data-storage/shared/media
You can also use the following Codelab (and the 5th step) to see an example specifically using CameraX: https://developer.android.com/codelabs/camerax-getting-started#4