Pages

Wednesday, July 9, 2014

[Android] Get access to external SD card

Have you ever used Environment.getExternalStorageDirectory()?  During the past, I had used it to get access to my SD card and it worked great!  However, some Android smartphones nowadays (2014) have a large internal storage and another external SD card slot.  When I use Environment.getExternalStorageDirectory() on these phones, it sometimes returns me the internal one, which is not what I want.

Below is the official document for Environment.getExternalStorageDirectory()
Return the primary external storage directory.

Hmmm...It says it will return external storage, great!  But, it actually returns the PRIMARY external storage, which is sometimes the embedded/internal storage

So, how can I get the path of my SD card without hardcoding the path into my codes?  Below is a naïve way:
String SD_PATH; if(Environment.isExternalStorageRemovable()){ SD_PATH = Environment.getExternalStorageDirectory().toString(); } else{ SD_PATH = System.getenv("SECONDARY_STORAGE"); } String primaryStoragePath = Environment.getExternalStorageDirectory().toString();

As you can see, the concept is quite so simple: If your primary storage is removable (not embedded), then it is a SD card for real.  Otherwise, we will search your second storage assuming there is no other storage available.


No comments:

Post a Comment