【问题标题】:Android 4.4+ : check if path is on secondary storageAndroid 4.4+:检查路径是否在辅助存储上
【发布时间】:2014-10-05 08:06:56
【问题描述】:

当 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+) 不同的奇怪安装点。

【问题讨论】:

    标签: android path storage android-4.4-kitkat getenv


    【解决方案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;
    }
    

    【讨论】:

    • getCanonicalPath() 是否总是产生以'/mnt' 开头的路径?这很重要。
    • getCanonicalPath() 将遵循任何符号链接,因此如果二级存储的真实路径不以 /mnt 开头,那么答案是否定的。不过没关系,因为您不会在其他任何地方使用 getCanonicalPath()。
    • 基于for (String path : paths) { File file = new File(path); if (file.isDirectory()) { return file; } } 为什么你能确定第一个元素是可移动的SD卡?谢谢。
    • 我记得这个解决方案之前是有效的,但是今天我在 ASUS_Z00LDD,android 版本 6.0.1 上再次测试它并且不工作。 System.getenv("SECONDARY_STORAGE") 只会产生:/storage/sdcard1 但当调用 file.isDirectory() 时,它不会将其识别为目录。真正的sd卡路径也是/storage/3FBF-1DF5/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多