确定SD卡是否已安装

时间:2015-01-06 00:57:53

标签: java android android-sdcard

我正在寻找一种方法来查找SD卡是否已安装。在其他人这样说之前, Environment.getExternalStorageState()不是答案

Environment.getExternalStorageState()将告诉您是否已装入主外部存储。这不一定(事实上,通常不是)SD卡。

EnvironmentCompat.getStorageState(文件文件)似乎可以工作,但如果该位置不是外部存储,则返回MEDIA_UNKNOWN - see here for proof

到目前为止,我最好的想法是尝试创建一个文件并将结果(成功或失败)作为MEDIA_MOUNTED或MEDIA_UNMOUNTED,但我想知道是否有人有更优雅的解决方案。

作为旁注,我目前使用的代码是否存在查找SD卡路径的问题?

    public static File getExternalFilesDir(Context context) {
    File extFiles[] = ContextCompat.getExternalFilesDirs(context, null);
    File sd = null;

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;

    if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        // Use the isExternalStorageRemovable function added in Lollipop
        for (File file : extFiles) {
            if (Environment.isExternalStorageRemovable(file)) {
                sd = file;
            }
        }

    } else if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT) {
        // getExternalFilesDirs will return all storages on KitKat. Assume
        // the second storage is the sd card
        if (Environment.isExternalStorageRemovable()) {
            sd = extFiles[0];
        } else if (extFiles.length > 2) {
            sd = extFiles[1];
        }

    } else if (currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        // Use the secondary storage if the primary one is not removable
        if (Environment.isExternalStorageRemovable()) {
            sd = extFiles[0];
        } else {
            String secStore = System.getenv("SECONDARY_STORAGE");
            String packageName = context.getPackageName();
            if (secStore != null) {
                sd = new File(secStore + "/Android/data/" + packageName + "/files");
            }
        }
    } else {
        // Froyo and Eclair do not have emulated storages
        sd = extFiles[0];
    }

    if (sd != null && !sd.exists()) {
        sd.mkdirs();
    }
    if (sd != null) {
        Log.v("getExternalFilesDir", sd.getAbsolutePath());
    }

    return sd;
}

0 个答案:

没有答案