安卓 4.4+ : check if path is on secondary storage

标签 android path storage android-4.4-kitkat getenv

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

注意:

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

  • 应用想像往常一样检查挂载的内容,例如在其插槽中插入外部 SD 卡时

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

最佳答案

这是我目前的解决方案。不理想,但应该可以。

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

关于安卓 4.4+ : check if path is on secondary storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25261178/

相关文章:

android - 无法解析 com.android.billingclient :billing:1. 1

powershell - 在 PowerShell 中使用 Get-ChildItem 时,如何获得询问路径的提示?

linux - 是否可以更改 gcc *默认* 库搜索路径?

mysql - 如何获取 MySQL 数据库的真实大小?

Android 内存类型(RAM v 内部存储器)

Android onScrollChanged() 未被调用

android - 通过蓝牙将 Android 连接到 Health Device

Android:拍照并保存到指定文件夹

android - 如何在 BlackBerry Priv 上调试我的 Android 应用程序?

algorithm - Prolog - 解决游戏,实现启发式