Wednesday, October 3, 2012

How to get all installed SD cards on Android

Today, I wanted to get all installed SD Cards on the device. In Android you can use Environment.getExternalStorageDirectory() get the  external device path but if you have more than 1, (in Galaxy S3 it has 2) you are in trouble. After few hours of Googling i managed to put this code together and hope it will help someone else too..

private static ArrayList<String> mMounts = new ArrayList<String>();
private void dumpAllSDCards() {
mMounts.add("/mnt/sdcard");
     
        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(" ");
lineElements[1].replaceAll(":.*$", "");
String element = lineElements[1];
                if (!element.equals("/mnt/sdcard")) mMounts.add(element);
              }
            }
          } catch (Exception e) {
           Log.d("MainActivity", e.toString());
          }
     
        for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
File root = new File(mount);
if (!root.exists() || !root.isDirectory() || !root.canWrite())
mMounts.remove(i--);
}
     

        for (String drive : mMounts) {
Log.d("MainActivity", drive + " exist!");
}     
}