How to save file to public (external) storage on Android Q (API 29)?

t.jancic picture t.jancic · Aug 13, 2019 · Viewed 8.5k times · Source

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?

Answer

Nauman Ash picture Nauman Ash · Feb 3, 2020

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
}