I have been using external storage in order to save a different type of files. That files needs to be visible to user. And now from Android Q, the method getExternalStoragePublicDirectory()
has been deprecated getExternalStoragePublicDirectory(docs).
I used following code:
File externalFilesDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DirectoryName");
Is there another way to save files which will be visible to user?
You need to add a check for Android Q. Let's assume you want to save the Image in your public Download folder.
try{
OutputStream fos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
} else {
String imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
File image = new File(imagesDir, fileName);
fos = new FileOutputStream(image);
}
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
}catch (IOException e) {
// Log Message
}