Android: storing files in Downloads

6.1k Views Asked by At

With Android 10 and scoped storage it's not possible to use Environment.getExternalStoragePublicDirectory() anymore. There are multiple other options, including MediaStore and Storage Access Framework. Our email app would like to only append new files to Downloads collection. We must pre-process them locally so we can't use DownloadManager.

MediaStorage guide mentions

Note: Although it's possible to store general-purpose files in either the Documents/ folder or the Download/ folder—including non-media files—it's better to use the Storage Access Framework (SAF) for these use cases.

But from what I understand from Storage Access Framework guide we would have to prompt user each time when they want to download a file and it seems unnecessary.

What is the common practice for appending files to Downloads?

2

There are 2 best solutions below

1
On

here is an exemple to write à file in download folder :

   OutputStream out;

   ContentResolver contentResolver = getContext().getContentResolver();

   ContentValues contentValues = new ContentValues();
   contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, localPath);
   contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
   contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_DOWNLOADS);
   Uri uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues);
   out = contentResolver.openOutputStream(uri);
1
On

You can save downloaded files to Download folder, regardless of the API levels:

FileDescription file = new FileDescription(fileName, subFolder, mimeType);
Uri fileUri = DocumentFileCompat.createDownloadWithMediaStoreFallback(context, file);

Open output stream with fileUri and write data into it.

Anyway, DocumentFileCompat is only available in SimpleStorage.