Search code examples
androidemulationsd-card

How to check Efficiently whether SD Card is Present and is Writable?


I am using following code to check whether the Sd Card is present and is Writable.But when i use that code in context of Sd Card of Emulator,it shows that the Sd Card is not present in the emulator but in reality,the File Explorer is showing the contents of the Sd Card of the corresponding Emulator.This is the code:

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    System.out.println("storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            System.out.println("storage writable  is " + writable );
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

This code is showing that the Sd Card is not Mounted But the File Explorer is showing the different picture.Please help me.Thanks in advance.


Solution

  • This work will work check both mounted and it is readable or not.

    private boolean isExternalStorageAvailable() {
    
            String state = Environment.getExternalStorageState();
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;
    
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
            } else {
                // Something else is wrong. It may be one of many other states, but
                // all we need
                // to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
            }
    
            if (mExternalStorageAvailable == true
                    && mExternalStorageWriteable == true) {
                return true;
            } else {
                return false;
            }
        }