运行Jellybean +的所有Android手机/存储是否通用?

时间:2017-07-15 08:04:02

标签: android

我想扫描存储空间以检索其扩展名与一组扩展名匹配的所有文件。

目前我正在使用Environment.getExternalStorageDirectory().getPath(),但它会返回三星Galaxy Core Prime上内置存储的路径(我还没有在其他设备上尝试过),并省去了外部SD卡。

但是,我发现路径/storage/是上述设备上内置存储和SD卡的根。所以我的问题是:在运行SDK 16 +的所有Android设备中它是否相同?

请确认所述路径存在,并且它是内置存储和外部SD卡(如果有)的根。

1 个答案:

答案 0 :(得分:0)

试试这段代码

private String[] getExternalStorageDirectoryn() {
    List<String> results = new ArrayList<>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //Method 1 for KitKat & above
        File[] externalDirs = getExternalFilesDirs(null);

        for (File file : externalDirs) {
            String path = file.getPath().split("/Android")[0];

            boolean addPath = false;

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                addPath = Environment.isExternalStorageRemovable(file);
            }
            else{
                addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file));
            }

            if(addPath){
                results.add(path);
            }
        }
    }

    if(results.isEmpty()) { //Method 2 for all versions

        String output = "";
        try {
            final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                output = output + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
        if(!output.trim().isEmpty()) {
            String devicePoints[] = output.split("\n");
            for(String voldPoint: devicePoints) {
                results.add(voldPoint.split(" ")[2]);
            }
        }
    }

    //Below few lines is to remove paths which may not be external memory card, like OTG (feel free to comment them out)
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        for (int i = 0; i < results.size(); i++) {
            if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}")) {
                Log.d("Storage", results.get(i) + " might not be extSDcard");
                results.remove(i--);
            }
        }
    } else {
        for (int i = 0; i < results.size(); i++) {
            if (!results.get(i).toLowerCase().contains("ext") && !results.get(i).toLowerCase().contains("sdcard")) {
                Log.d("Storage", results.get(i)+" might not be extSDcard");
                results.remove(i--);
            }
        }
    }

    String[] storageDirectories = new String[results.size()];
    for(int i=0; i<results.size(); ++i) storageDirectories[i] = results.get(i);

    return storageDirectories;

}