Stack Overflow archive
1 score

Android 4.4+ : check if path is on secondary storage

score
1
question views
2.8K
license
CC BY-SA 3.0

Here is my current solution. Not ideal, but it should work.

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

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.