以编程方式检查SD卡是否可用

时间:2011-09-15 10:14:19

标签: android sd-card

我的应用适用于只有SD卡的手机。因此,我想以编程方式检查SD卡是否可用以及如何找到SD卡可用空间。有可能吗?

如果是,我该怎么做?

12 个答案:

答案 0 :(得分:126)

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
}

答案 1 :(得分:13)

接受的答案对我不起作用

public class DataPointToStringConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        DataPoint point = (DataPoint)values[0];
        List<DataPoint> points = ((IEnumerable<DataPoint>)values[1]).ToList();
        return (points.IndexOf(point) + 1).ToString() +"-  (" + point.X.ToString() + " , " + point.Y.ToString() + ")";
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    } 
}

如果设备具有内置存储,则返回true; 我的解决方案是检查外部文件目录的数量,如果有多个,则设备有sdcard。 它可以工作,我测试了几个设备。

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

答案 2 :(得分:12)

"Using the External Storage"

中所述使用Environment.getExternalStorageState()

要获得外部存储空间,请使用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();

答案 3 :(得分:5)

我为检查存储状态写了一个小课程。也许这对你有用。

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;
}
}
}

答案 4 :(得分:4)

我修改了它,如果存在SD卡,它会设置那里的路径。如果没有,则将其设置在内部目录中。

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

答案 5 :(得分:4)

您可以检查外部可移动SD卡是否可用,如

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;

}

这完全符合我的测试。

答案 6 :(得分:3)

 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);
}

答案 7 :(得分:1)

这个简单的方法对我有用。在所有类型的设备中测试过。

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;
    }
  }

答案 8 :(得分:0)

我创建了一个类来检查SD卡上的文件夹是否可用:

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);
    }
}

答案 9 :(得分:0)

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

即使存在sd卡且处于弹出状态,此功能也可以正常工作

 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");

            }

答案 10 :(得分:0)

科特琳

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

答案 11 :(得分:0)

  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;
   }