Find location of a removable SD card

前端 未结 22 2607
南方客
南方客 2020-11-21 11:32

Is there an universal way to find the location of an external SD card?

Please, do not be confused with External Storage.

Environment.getExternalStorage

22条回答
  •  长发绾君心
    2020-11-21 11:59

    If you look at the source code for android.os.Environment you will see that Android relies heavily on environment variables for paths. You can use the "SECONDARY_STORAGE" environment variable to find the path to the removable sd card.

    /**
     * Get a file using an environmental variable.
     *
     * @param variableName
     *         The Environment variable name.
     * @param paths
     *         Any paths to the file if the Environment variable was not found.
     * @return the File or {@code null} if the File could not be located.
     */
    private static File getDirectory(String variableName, String... paths) {
        String path = System.getenv(variableName);
        if (!TextUtils.isEmpty(path)) {
            if (path.contains(":")) {
                for (String _path : path.split(":")) {
                    File file = new File(_path);
                    if (file.exists()) {
                        return file;
                    }
                }
            } else {
                File file = new File(path);
                if (file.exists()) {
                    return file;
                }
            }
        }
        if (paths != null && paths.length > 0) {
            for (String _path : paths) {
                File file = new File(_path);
                if (file.exists()) {
                    return file;
                }
            }
        }
        return null;
    }
    

    Example usage:

    public static final File REMOVABLE_STORAGE = getDirectory("SECONDARY_STORAGE");
    

提交回复
热议问题