2014年4月9日 星期三

Get real external storage path for lower Android 4.4

The new Android version has emulated sdcard.
We usually get external storage path by  API - 'Environment.getExternalStorageDirectory();' .
Sometimes, the API apply a internal storage that means it's emulated external storage.
So I find a way to get real external storage on the Internet, the full code is following:
/**
 * Get real external storage  path.
 * @return Real external storage path or null for no external storage.
 */
private static String getSdcardPath(){
 File file = new File("/system/etc/vold.fstab");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(file);
            if (fr != null) {
                br = new BufferedReader(fr);
                String s = br.readLine();
                while (s != null) {
                    if (s.startsWith("dev_mount")) {
                        String[] tokens = s.split("\\s");
                        String path = tokens[2]; //mount_point
                        br.close();
                        fr.close();
                        return path;
                    }
                    s = br.readLine();
                }
                br.close();
                fr.close();
            }//if (fr != null)
        } 
        catch (FileNotFoundException e) {} 
        catch (IOException e) {} 
        return null;
}
If you want to read file from external storage, remember to add user-permission "android.permission.READ_EXTERNAL_STORAGE".
For writing file, adding user-permission "android.permission.WRITE_EXTERNAL_STORAGE".

If you add "android.permission.WRITE_EXTERNAL_STORAGE", it explicitly add "android.permission.READ_EXTERNAL_STORAGE".

沒有留言 :

張貼留言