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:
- My current workaround is to avoid
scanFile
for directories. - 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. - Renaming files with Windows Explorer that actually are directories does not restore them. Even after Reboot.
This line as suggested in https://mcmap.net/q/144026/-nexus-4-not-showing-files-via-mtp 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()));
Maybe related:
- https://mcmap.net/q/144026/-nexus-4-not-showing-files-via-mtp
- Using content resolver for all sorts of File operations like deleting a file in this answer: Android Deleting Files MediaScannerConnection