Check whether the SD card is available or not programmatically

AndroidSd Card

Android Problem Overview


My app is working for mobiles which have an SD card only. So programmatically I want to check if the SD card is available or not and how to find the SD card free space. Is it possible?

If yes, how do I do it?

Android Solutions


Solution 1 - Android

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
Boolean isSDSupportedDevice = Environment.isExternalStorageRemovable();

if(isSDSupportedDevice && isSDPresent)
{
  // yes SD-card is present
}
else
{
 // Sorry
}

Solution 2 - Android

Accepted answer doesn't work for me

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

In case if device has a built-in storage, it returns true; My solution is that to check the external files directory count, if there is more than one, device has sdcard. It works and I tested it for several devices.

public static boolean hasRealRemovableSdCard(Context context) {
    return ContextCompat.getExternalFilesDirs(context, null).length >= 2;
}

Solution 3 - Android

Use Environment.getExternalStorageState() as described in "Using the External Storage".

To get available space on external storage, use StatFs:

// do this only *after* you have checked external storage state:
File extdir = Environment.getExternalStorageDirectory();
File stats = new StatFs(extdir.getAbsolutePath());
int availableBytes = stats.getAvailableBlocks() * stats.getBlockSize();

Solution 4 - Android

You can check if external removable sd card is available like this

public static boolean externalMemoryAvailable(Activity context) {
    File[] storages = ContextCompat.getExternalFilesDirs(context, null);
    if (storages.length > 1 && storages[0] != null && storages[1] != null)
        return true;
    else
        return false;
 
}

This works perfectly as i have tested it.

Solution 5 - Android

I wrote a little class for that checking the storage state. Maybe it's of some use for you.

import android.os.Environment;

/**
 * Checks the state of the external storage of the device.
 * 
 * @author kaolick
 */
public class StorageHelper
{
// Storage states
private boolean externalStorageAvailable, externalStorageWriteable;

/**
 * Checks the external storage's state and saves it in member attributes.
 */
private void checkStorage()
{
// Get the external storage's state
String state = Environment.getExternalStorageState();

if (state.equals(Environment.MEDIA_MOUNTED))
{
    // Storage is available and writeable
    externalStorageAvailable = externalStorageWriteable = true;
}
else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
{
    // Storage is only readable
    externalStorageAvailable = true;
    externalStorageWriteable = false;
}
else
{
    // Storage is neither readable nor writeable
    externalStorageAvailable = externalStorageWriteable = false;
}
}

/**
 * Checks the state of the external storage.
 * 
 * @return True if the external storage is available, false otherwise.
 */
public boolean isExternalStorageAvailable()
{
checkStorage();

return externalStorageAvailable;
}

/**
 * Checks the state of the external storage.
 * 
 * @return True if the external storage is writeable, false otherwise.
 */
public boolean isExternalStorageWriteable()
{
checkStorage();

return externalStorageWriteable;
}

/**
 * Checks the state of the external storage.
 * 
 * @return True if the external storage is available and writeable, false
 *         otherwise.
 */    
public boolean isExternalStorageAvailableAndWriteable()
{
checkStorage();

if (!externalStorageAvailable)
{
    return false;
}
else if (!externalStorageWriteable)
{
    return false;
}
else
{
    return true;
}
}
}

Solution 6 - Android

I modified it such that if an SD card exists, it sets the path there. If not, it sets it at the internal directory.

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
    path = theAct.getExternalCacheDir().getAbsolutePath() + "/GrammarFolder";
}
else
{
    path = theAct.getFilesDir() + "/GrammarFolder";
}

Solution 7 - Android

 void updateExternalStorageState() {
     String state = Environment.getExternalStorageState();
     if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
       mExternalStorageWriteable = false;
     } else {
       mExternalStorageAvailable = mExternalStorageWriteable = false;
}
handleExternalStorageState(mExternalStorageAvailable,
        mExternalStorageWriteable);
}

Solution 8 - Android

This simple method is worked for me. Tested in all type of devices.

public boolean externalMemoryAvailable() {
    if (Environment.isExternalStorageRemovable()) {
      //device support sd card. We need to check sd card availability.
      String state = Environment.getExternalStorageState();
      return state.equals(Environment.MEDIA_MOUNTED) || state.equals(
          Environment.MEDIA_MOUNTED_READ_ONLY);
    } else {
      //device not support sd card. 
      return false;
    }
  }

Solution 9 - Android

Kotlin

fun Context.externalMemoryAvailable(): Boolean {
    val storages = ContextCompat.getExternalFilesDirs(this, null)
    return storages.size > 1 && storages[0] != null && storages[1] != null
}

Solution 10 - Android

  public static boolean hasSdCard(Context context) {

    File[] dirs = context.getExternalFilesDirs("");        
    if(dirs.length >= 2 && dirs[1]!=null){
        if(Environment.isExternalStorageRemovable(dirs[1])){ // Extra Check
            return true;
        }
     }
    return false;
   }

Solution 11 - Android

I created a class to check if the folder on the SD card is available or not:

public class GetFolderPath {

    static String folderPath;

    public static String getFolderPath(Context context) {
        if (isSdPresent() == true) {
            try {
                File sdPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FolderName");
                if(!sdPath.exists()) {
                    sdPath.mkdirs();
                    folderPath = sdPath.getAbsolutePath();
                } else if (sdPath.exists()) {
                    folderPath = sdPath.getAbsolutePath();
                }
            }
            catch (Exception e) {

            }
            folderPath = Environment.getExternalStorageDirectory().getPath()+"/FolderName/";
        }
        else {
            try {
                File cacheDir=new File(context.getCacheDir(),"FolderName/");
                if(!cacheDir.exists()) {
                    cacheDir.mkdirs();
                    folderPath = cacheDir.getAbsolutePath();
                } else if (cacheDir.exists()) {
                    folderPath = cacheDir.getAbsolutePath();
                }
            }
            catch (Exception e){

            }
        }
        return folderPath;
    }

    public static boolean isSdPresent() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }
}

Solution 12 - Android

** i fixed this with help of @Jemo Mgebrishvili answer** 

this works perfectly even if sd card is present and in the ejected state

 if (ContextCompat.getExternalFilesDirs(this, null).length >= 2) {
                File[] f = ContextCompat.getExternalFilesDirs(this, null);
                for (int i = 0; i < f.length; i++) {
                    File file = f[i];
                    if(file!=null && i ==1)
                    {
                        Log.d(TAG,file.getAbsolutePath()+ "external sd card  available");
    
                    }
    
                }
            } else {
                Log.d(TAG, " external sd card not available");
    
            }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnareshView Question on Stackoverflow
Solution 1 - AndroidParesh MayaniView Answer on Stackoverflow
Solution 2 - AndroidJemo MgebrishviliView Answer on Stackoverflow
Solution 3 - AndroidPhilipp ReichartView Answer on Stackoverflow
Solution 4 - AndroidJauraView Answer on Stackoverflow
Solution 5 - AndroidkaolickView Answer on Stackoverflow
Solution 6 - AndroidArdaAView Answer on Stackoverflow
Solution 7 - AndroidUmeshView Answer on Stackoverflow
Solution 8 - AndroidKishan VaghelaView Answer on Stackoverflow
Solution 9 - AndroidSK PanchalView Answer on Stackoverflow
Solution 10 - AndroidAshish TyagiView Answer on Stackoverflow
Solution 11 - AndroidUchihaSasukeView Answer on Stackoverflow
Solution 12 - AndroidRajesh WolfView Answer on Stackoverflow