Android and MTP (programmer’s view)

In Android 3.x, Google switched from USB Mass Storage to MTP for files stored in the “external storage”. For any device created before Android 3.x, creating a file and copying it off the device was easy:

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

This would place a file called test.txt in the directory My App on the SD card/external storage. You then would connect your Android device via USB with your computer, enable USB mass storage, and simply copy the file off the device.

USB mass storage on Android

With newer devices (like the Galaxy Nexus I’m using) that’s no longer enough because they use MTP instead of USB Mass Storage. 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).

MTP on Android

To make the file show up, after closing it use the following code (API documentation):

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

After doing this the file should appear immediately in the Windows Explorer.

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.