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

时间:2014-12-09 12:52:55

标签: android sd-card

虽然我有这么多帖子但是问题就是这样  如果手机有内置存储,则返回true。 任何人帮助我

2 个答案:

答案 0 :(得分:1)

像这样使用:

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

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

答案 1 :(得分:0)

下面的代码将有助于......

/**
 * Returns all available external SD-Card roots in the system.
 *
 * @return paths to all available external SD-Card roots in the system.
 */
public static String[] getStorageDirectories() {
    String[] storageDirectories;
    String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        List<String> results = new ArrayList<String>();
        File[] externalDirs = myContext.getExternalFilesDirs(null);
        for (File file : externalDirs) {
            String path = null;
            try {
                path = file.getPath().split("/Android")[0];
            } catch (Exception e) {
                e.printStackTrace();
                path = null;
            }
            if (path != null) {
                if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
                        || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)) {
                    results.add(path);
                }
            }
        }
        storageDirectories = results.toArray(new String[0]);
    } else {
        final Set<String> rv = new HashSet<String>();

        if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
            final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
            Collections.addAll(rv, rawSecondaryStorages);
        }
        storageDirectories = rv.toArray(new String[rv.size()]);
    }
    return storageDirectories;
}

//检查外部SD是否可用

    String retArray[] = getStorageDirectories();
    if (retArray.length == 0) {
        Toast.makeText(ListenActivity.this, "Sdcard not Exists", Toast.LENGTH_SHORT).show();
    } else {
        for (int i = 0; i < retArray.length; i++) {              
            Log.e("path ", retArray[i]);
            }
    }