Thursday, January 22, 2009

Where is my sd card?

Today I was testing how to detect if the sd card was present or not. The most obvious way to do this would be to create a File and point it to /sdcard.

File mFile = new File(/sdcard/mydir);

Next you would check if the file exists(), isDirectory(), canWrite() etc... to see if you actually have permission to create and store your data. However these methods will return true even if the sd card is not present. It's not until you actually try to write some data that you will see errors.

The trick to detecting the sd card correctly is to use android.os.Environment method getExternalStorageState(). This will return the current state of external storage, i.e. mounted, unmounted plus many other states.

So to test if external storage is present we can use the following snippet (sorry I have no idea how to format code on this blog)

boolean canSaveExternal = false;

String storageState = Environment.getExternalStorageState();

if (
canSaveExternal = true;
canSaveExternal = false;

I imagine in the future Android will have various external storage devices so getExternalStorageDirectory() will be useful to know where to save data.

No comments: