Skip to content

Instantly share code, notes, and snippets.

@ZhDev
Created January 2, 2013 13:27
Show Gist options
  • Save ZhDev/4434569 to your computer and use it in GitHub Desktop.
Save ZhDev/4434569 to your computer and use it in GitHub Desktop.
Returns a set of paths (as Strings) to the volumes mounted in an android device as external storage (such as SD cards and pendrives)
private TreeSet<String> getMountedSdCards() {
String externalMain = Environment.getExternalStorageDirectory().getAbsolutePath();
TreeSet<String> mountPaths = new TreeSet<String>();
try {
Scanner scanner = new Scanner(new File("/proc/mounts"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
if (!element.equals(externalMain)) {
mountPaths.add(element);
}
}
}
} catch (Exception e) {
// TODO Error
}
TreeSet<String> voldPaths = new TreeSet<String>();
try {
Scanner scanner = new Scanner(new File("/system/etc/vold.fstab"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":")) {
element = element.substring(0, element.indexOf(":"));
}
if (!element.equals(externalMain)) {
voldPaths.add(element);
}
}
}
} catch (Exception e) {
// TODO Error
}
TreeSet<String> intersection = new TreeSet<String>(mountPaths);
intersection.retainAll(voldPaths);
Iterator<String> iterator = intersection.iterator();
while (iterator.hasNext()) {
String path = iterator.next();
File pathFile = new File(path);
if (!pathFile.exists() || !pathFile.isDirectory() /* || !pathFile.canWrite() */) {
iterator.remove();
}
}
return intersection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment