Folder added on Android is not visible via USB

android, filesystems

Solution

None of the above helped me, but this worked: The trick being to NOT scan the new folder, but rather create a file in the new folder and then scan the file. Now Windows Explorer sees the new folder as a true folder.

    private static void fixUsbVisibleFolder(Context context, File folder) {
    if (!folder.exists()) {
        folder.mkdir();
        try {
            File file = new File(folder, "service.tmp");//workaround for folder to be visible via USB
            file.createNewFile();
            MediaScannerConnection.scanFile(context,
                    new String[]{file.toString()},
                    null, (path, uri) -> {
                        file.delete();
                        MediaScannerConnection.scanFile(context,
                                new String[]{file.toString()} ,
                                null, null);
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Thanks to https://issuetracker.google.com/issues/37071807#comment90

You also should scan every created file in the directory analogically:

   private static void fixUsbVisibleFile(Context context, File file) {
    MediaScannerConnection.scanFile(context,
            new String[]{file.toString()},
            null, null);
}

Problem

I'm trying to save pictures in a subfolder on Android. Here's a bit of my code: ``` File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); path = new File(path, "SubDirName"); path.mkdirs(); ``` (I've tried `getExternalStorageDirectory` instead of `getExternalStoragePublicDirectory` and the Pictures folder instead of DCIM.) Any subfolder I add, including its contents, don't show up in Windows Explorer when the device is connected via USB. It does show in the Android File Manager, though. I've tried broadcasting the `ACTION_MEDIA_MOUNTED` intent on the new directory's parent. It didn't work. If I add a file in Windows, it shows up on Android. If I add a file on Android via the File Manager, it shows up in Windows. If I add the file programmatically, it shows up on the Android File Manager, but not in Windows Explorer. And I need to get it from Windows, and I don't want the final user to have to create the folder manually. What am I doing wrong?

Original source

Related problems