2014年8月24日 星期日

MTP on Android

What is MTP?

MTP stands for “Media Transfer Protocol.” After Android 3.x, Android uses this protocol, it appears to the computer as a “media device.” The media transfer protocol was widely promoted as a standardized protocol for transferring audio files to digital music players using Windows Media Player and similar applications. It was designed to allow other media player companies to compete with Apple’s iPod and iTunes.

The Problem in MTP

File dir = Environment.getExternalStoragePublicDirectory("TempDir");
File file = new File(dir, "test.txt");
FileUtils.writeStringToFile(file, "Hello World");

If you’d execute the code above, the file would be created but it wouldn’t show up in the Windows Explorer (or whatever tool you’re using the view the device’s contents).
To make the file show up, after closing it use the following code (API documentation):
MediaScannerConnection.scanFile(ctx, new String[] { file.getAbsolutePath() }, null, null);

Notes:
The external storage is scanned automatically when the Android device is booting (e.g. after a restart).
If you pass a directory (instead of a file) to scanFile(), the directory will show up as file in Window Explorer, so don’t do this.