Search code examples
androidandroid-external-storageandroid-mediascanner

File saved to Download folder doesn't show up in "Downloads" app


I'm trying to save a file to the Download folder. I get the directory and save the file using something like this:

File exportDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "");
if (!exportDir.exists()) {
    exportDir.mkdirs();
}
File file = new File(exportDir, "filename.csv");
try {
    if (file.exists()) {
        // if the file exists create new file will do nothing. We want to
        // overwrite contents every time
        file.delete();
    }
    boolean created = file.createNewFile();
    if (!created) {
        Log.d("", "Failed to create file");
    }

    // .. write to file

    MediaScannerConnection.scanFile(activity, new String[]{exportDir.getPath()}, null, null);
} catch (Exception sqlEx) {
    Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}

I've tested this on three devices:

  • OnePlus 3 (Android 8.0.0)
  • Blu Advance 5.0 (Android 5.1)
  • Samsung Galaxy S3 (Android 4.4.4)

On all devices if I navigate to /storage/sdcard0/Download or something of the like I can see my file there. HOWEVER if I try to open the native "Downloads" app I cannot see the file on the Blu or the Galaxy but I can see it on my OnePlus 3.

I have tried restarting the phones to trigger a media scan and have tried using MediaScannerConnection.scanFile to scan both the file and the folder with no luck. According to FileManager the file is -rw-rw---- just like most of the other files in that folder so what is going on here?

My goal is to save the file to a logical place where the user can easily find it and pull it off of their phone. Does the Downloads folder have special rules?

Any suggestions would be appreciated.


Solution

  • Does the Downloads folder have special rules?

    The Downloads/ folder on external storage does not. The Downloads app does. The classic Downloads app is for files downloaded via DownloadManager, though that can be modified by device manufacturers as they see fit.

    My goal is to save the file to a logical place where the user can easily find it and pull it off of their phone.

    Downloads/ may or may not be the best place — it is not my first choice for something that the user is not explicitly downloading from an app.

    UPDATE 2023-07-29: the storage rules are frightfully complicated now. I strongly recommend that you let the user choose where to save the content, via ACTION_CREATE_DOCUMENT / ActivityResultContracts.CreatedDocument or ACTION_OPEN_DOCUMENT_TREE / ActivityResultContracts.OpenDocumentTree.