2

当 Android 版本为 4.4+ 时,我的应用程序必须检查某个文件夹是否在辅助存储中。

我正在使用这个:

private boolean isPathOnSecondaryStorage(String path) {
    boolean res=false;
    String secondaryStorage=System.getenv("SECONDARY_STORAGE");
    String[] secondaryPaths=secondaryStorage.split(":");
    for (int i=0;i<secondaryPaths.length;i++) {
        String secondaryPath=secondaryPaths[i].trim();
        if (path.contains(secondaryPath)) {
            res=true;
        }
    }
    return res;
}

注意:

  • 路径由用户通过文件选择器活动选择,从 /mnt 开始

  • 该应用程序想要像往常一样检查安装的内容,例如将外部 SD 卡插入其插槽时

所以我问上面提到的代码是否总是能够检测到路径何时在辅助存储上,或者在某些设备上它可以找到与 /mnt (Android 4.4+) 不同的奇怪安装点。

4

1 回答 1

1

这是我目前的解决方案。不理想,但它应该工作。

/**
 * Uses the Environmental variable "SECONDARY_STORAGE" to locate a removable micro sdcard
 * 
 * @return  the primary secondary storage directory or
 *          {@code null} if there is no removable storage
 */
public static File getRemovableStorage() {
    final String value = System.getenv("SECONDARY_STORAGE");
    if (!TextUtils.isEmpty(value)) {
        final String[] paths = value.split(":");
        for (String path : paths) {
            File file = new File(path);
            if (file.isDirectory()) {
                return file;
            }
        }
    }
    return null;
}

/**
 * Checks if a file is on the removable SD card.
 * 
 * @see {@link Environment#isExternalStorageRemovable()}
 * @param file a {@link File}
 * @return {@code true} if file is on a removable micro SD card, {@code false} otherwise
 */
public static boolean isFileOnRemovableStorage(File file) {
    final File microSD = getRemovableStorage();
    if (microSD != null) {
        String canonicalPath;
        try {
            canonicalPath = file.getCanonicalPath();
            if (canonicalPath.startsWith(microSD.getAbsolutePath())) {
                return true;
            }
        } catch (IOException e) {
        }
    }
    return false;
}
于 2014-08-12T09:57:55.393 回答