gyanesh
gyanesh

Reputation: 1

How to find whether the SD card is present or not via code/API in Android?

How to get the status whether a SD card is mounted/inserted in Android device or not. The following is always returning TRUE:

android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)

There are several post related to this, but I couldn't find a manufacturer-independent solution.

Upvotes: 0

Views: 342

Answers (1)

StenSoft
StenSoft

Reputation: 9609

Android API: Iterate through all external storages obtainable with getExternalStoragePublicDirectory, calling isExternalStorageRemovable on each of them. When you find one, ask if it is mounted with getExternalStorageState. However, it may happen that the SD card is not used for any external storage directory and so you would not find it.

fstab: Parse /etc/vold.fstab, find mount points, ask if they are removeable with isExternalStorageRemovable and check their state with getExternalStorageState. Because it does not use public API, it may not work correctly in some versions of Android, including future ones. It may not work when the SD card is not used for any external storage either.

mounts: Parse /proc/mounts and do the same as for fstab but that may not work if the SD card is not used for any external storage. Or search for any partition using vfat but that may return false positives. /proc/mounts is a public Linux API so it is present in the same format everywhere. If no SD card can be found there, it is impossible to distinguish whether the SD card is unmounted or not supported at all.

However, there's really no reason to need that (and that's why there is no simple API for it). When you want to put some content in an external storage, you should use the appropriate directory provided by getExternalStoragePublicDirectory, disregarding whether it is an SD card or not.

Upvotes: 1

Related Questions