MTP, External Storage, and Your App
NOTE: This post originally appeared on the Appaholics blog as a guest post
Some changes in Android 3.x may impact your application, if you are writing content to external storage and want users to be able to access those files on their desktops or notebooks.
Android 3.0 switched the means by which users mount external storage and make it available to their desktop or notebook. Previously, Android used USB Mass Storage Mode, the same protocol used by USB thumb drives and the like. This is why when the external storage was unavailable when a host machine had it mounted — USB Mass Storage Mode was not designed for intelligent storage devices.
Android 3.0 now uses the Media Transfer Protocol as the way external storage gets mounted. Much of what has been written about this has focused on the user experience, such as needing third-party software to use MTP on OS X and Linux.
However, there is a more subtle shift that is important to developers: the
MTP contents are not based on the literal contents of external storage.
Instead, MTP contents are based on what files have been scanned by
MediaScannerConnection
. If you write a file to external storage, until and
unless that file is scanned by MediaScannerConnection
, it will not be
visible to users over MTP.
External storage is scanned on a reboot and possibly on a periodic basis.
Users can manually force a scan via utilities like SDRescan.
However, the best answer is for you to use scanFile()
on MediaScannerConnection
to update the media database after you close your file. This will make your file
immediately available to the user.
Previously, we only needed MediaScannerConnection
for actual “media”, such
as MP3 files or MP4 videos. Now, we need it for everything, if we want to give
the user immediate results.
On a related note, it may be that Android 3.0 or 3.1 would filter MTP and not
show the contents of directories that contain .nomedia
files, applying the
same rules that filter those out of things like the Music app. By Android 3.2
— at least based on light testing with the XOOM — that filtering
has been lifted. MTP shows everything, while .nomedia
still filters out
content from installed media-consuming applications.