Folder added on Android is not visible via USB

后端 未结 8 927
青春惊慌失措
青春惊慌失措 2020-11-30 01:18

I\'m trying to save pictures in a subfolder on Android. Here\'s a bit of my code:

File path = Environment.getExternalStoragePublicDirectory(Environment.DIREC         


        
相关标签:
8条回答
  • 2020-11-30 01:54

    The only thing that worked for me was this:

    Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri fileContentUri = Uri.fromFile(path);
    mediaScannerIntent.setData(fileContentUri);
    this.sendBroadcast(mediaScannerIntent);
    

    Credit to https://stackoverflow.com/a/12821924/1964666

    0 讨论(0)
  • 2020-11-30 01:59

    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);
    }
    
    0 讨论(0)
提交回复
热议问题