Android Tutorial: Check SD Card Status

 ·  · 

Before reading or writing Android SD card (external storage), you should check the status of SD card first.

Environment.getExternalStorageState() will return current status of Android SD card. Some important status are as follows.

  • Environment.MEDIA_UNKNOWN: the SD card cannot be recognized;
  • Environment.MEDIA_REMOVED: there is no available SD card;
  • Environment.MEDIA_UNMOUNTED: the SD card exists but not mounted yet. This status was deprecated in Android 4.0+;
  • Environment.MEDIA_CHECKING: Android system is preparing SD card, e.g. while device is powered on or booting;
  • Environment.MEDIA_MOUNTED: the SD card was mounted and was ready to use;
  • Environment.MEDIA_MOUNTED_READ_ONLY

Demo source code to check SD card status.

import android.os.Environment;

private boolean checkSDCardStatus() {
    String SDCardStatus = Environment.getExternalStorageState();

    // MEDIA_UNKNOWN: unrecognized SD card
    // MEDIA_REMOVED: no SD card
    // MEDIA_UNMOUNTED: SD card exists but not mounted, deprecated in Android 4.0+
    // MEDIA_CHECKING: preparing SD card
    // MEDIA_MOUNTED: mounted and ready to use
    // MEDIA_MOUNTED_READ_ONLY
    switch (SDCardStatus) {
        case Environment.MEDIA_MOUNTED:
            return true;
        case Environment.MEDIA_MOUNTED_READ_ONLY:
            Toast.makeText(this, "SD card is ready only.", Toast.LENGTH_LONG).show();
            return false;
        default:
            Toast.makeText(this, "SD card is not available.", Toast.LENGTH_LONG).show();
            return false;
    }
}

If the SD card is available, you can get the encapsulated java.io.File object of the SD card.

if (this.checkSDCardStatus()) {
    File file = Environment.getExternalStorageDirectory();
    Toast.makeText(this, file.getAbsolutePath(), Toast.LENGTH_LONG).show();
}