2012年11月8日 星期四

How to get SD Card directory

The official method Environment.getExternalStorageDirectory() seems to be not working for some Phone as this method return primary memory.

“In devices with multiple ‘external’ storage directories (such as both secure app storage and mountable shared storage), this directory represents the ‘primary’ external storage that the user will interact with.”.


Searching in internet and found the following code can find the SD Card directory.

        File file = new File("/system/etc/vold.fstab");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            if (fr != null) {
                br = new BufferedReader(fr);
                String s = br.readLine();
                while (s != null) {
                    if (s.startsWith("dev_mount")) {
                        String[] tokens = s.split("\\s");
                        path = tokens[2]; //mount_point
                        if (!Environment.getExternalStorageDirectory().getAbsolutePath().equals(path)) {
                            break;
                        }
                    }
                    s = br.readLine();
                }
            }           
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }           
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

沒有留言:

張貼留言