Andrei Herford Andrei Herford - 9 months ago 22
Android Question

How to create files/folders in external storage that are accessible via USB?

I am using a Nexus 5 as test device for my first Android app. When I connect the phone to my PC via USB, it pops up in the explorer and I can access different files and folder on the devices (just as if the device would be an USB stick...).

I thought that these files and folders would represent the

External Storage
and every file/folder my app stores in
External Storage
would be accessible via USB as well.

While creating files/folder in
External Storage
in my app is no problem, these files are not visible in the files and folders that can be accessed via USB:

public static File getAppPuplicExternalStorageDir() {
File appDir = null;

try {
appDir = new File(Environment.getExternalStorageDirectory(), "MyApp");
appDir.mkdirs();
}
catch (Exception e) { }

return appDir;
}


...
File noMediaFile = new File(getAppPuplicExternalStorageDir(), ".nomedia");
noMediaFile.createNewFile();
...


This code workes perfectly. I can test if the file exist, delete the file, create other files, etc. without any problem.

When I check the appDir it has the path
/storage/emulated/0/MyApp/
. Everything works fine, except that this folder is not visible via USB.

Is there a difference between the external storage and the files/folder that are visibel via USB? The user should be able to download the files to his PC. How can I manage to make my files visible via USB?

Answer Source

these files are not visible in the files and folders that can be accessed via USB

They will be, once MediaScannerConnection has indexed them. You can use scanFile() on MediaScannerConnection to make that happen faster.

Also note that the user may need to use a "refresh" or "reload" option in their MTP client (e.g., Windows Explorer) to see the files, or possibly even unplug/re-plug in the device, as some MTP clients cache directory listings.

When I check the appDir it has the path /storage/emulated/0/MyApp/. Everything works fine, except that this folder is not visible via USB.

That would be a MyApp/ directory under the root of external storage, at least for phones. For tablets with secondary users, the MyApp/ directory will be visible for the user when the user has logged into the tablet. The storage/emulated/0/ path is dynamic, to route your app's code to write to the right spot.

Also, please try not to use getExternalStorageDirectory() and clutter up the user's external storage. If these are files that the user should be manipulating, try to put them in a location specified by Environment.getExternalStoragePublicDirectory().