MediaScannerConnection#scanFile converts directories into files when accessing them with USB-MTP on Android 5 Lollipop

流过昼夜 提交于 2019-11-28 03:35:40

问题


Changes like renaming a file triggered by an app only appear to the USB-MTP interface after reboot of the Android device or after you registered the new file at the MediaScanner them like this (see Trigger mediascanner on specific path (folder), how to?):

file.renameTo(newFile);    
MediaScannerConnection.scanFile(context,
        new String[] { newFile.getAbsolutePath() }, null, null);

USB-MTP is used to access the storage of an android device via USB. E.g. with the Windows Explorer.

However, with the Sony XPERIA Tablet Z (SGP321) under Android 5.0.2 (Build 10.6.A.0.454) folders supplied in newFile will become a file with 4KB. I am no more able to access the folder structure using Windows Explorer anymore, nor can I copy the file to my computer. Even after reboot of the tablet! The same device with Android 4.4.4 does not show the behavior. It appears that only the USB-MTP view is broken. The file structure accessed by an android app still looks fine.

Question: Is this behavior a bug or did I implement it incorrectly? What would be the correct implementation?

What I've tried so far to fix the issue:

  1. My current workaround is to avoid scanFile for directories.
  2. I can convert files back into directories by renaming them with an android app without MediaScannerConnection#scanFile. After reboot, I can access the directory with Windows Explorer again.
  3. Renaming files with Windows Explorer that actually are directories does not restore them. Even after Reboot.
  4. This line as suggested in https://stackoverflow.com/a/21918085/433718 does not refresh USB-MTP view, but also does not convert directories into files:

    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(newFile.getParentFile()));
    
  5. Maybe related:

    • https://stackoverflow.com/a/27321544/433718
    • Using content resolver for all sorts of File operations like deleting a file in this answer: Android Deleting Files MediaScannerConnection

回答1:


I ended up creating a dummy text file in each directory I wanted to make visible, and use scanFile on the file.

1) create directory, but don't "scan" directories

2) copy file to directory

3) run scanFile on the filePath

MediaScannerConnection.scanFile (_application, new String[] { filePath }, null, null);


来源:https://stackoverflow.com/questions/31157882/mediascannerconnectionscanfile-converts-directories-into-files-when-accessing-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!