Android手機支持SDcard。目前很多手機廠商把SDcard集成到手機中,當然有的手機同時也支持可插拔的SDcard。這就有了內置SDcard和位置SDcard之分。
當手機同時支持內置和外置SDcard時:
調用系統API:Environment.getExternalStorageDirectory().getPath();得到的是SDcard路徑為內置的SDcard路徑。由於Android系統的碎片話,很多手機廠商處理SDcard的路徑都不相同,也沒有辦法通過/system/etc/vold.fstab文件中的配置信息來確定SDcard的路徑,因為這個文件的名字也不唯一。
自己研究了一下,獲取外置SDcard路徑的方法如下:
/** * 獲取外置SD卡路徑 * * @return */ public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime();// 返回與當前 Java 應用程序相關的運行時對象 try { Process p = run.exec(cmd);// 啟動另一個進程來執行命令 BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { // 獲得命令執行后在控制台的輸出信息 LOG.i("CommonUtil:getSDCardPath", lineStr); if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } // 檢查命令是否執行失敗。 if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常結束,1:非正常結束 LOG.e("CommonUtil:getSDCardPath", "命令執行失敗!"); } } inBr.close(); in.close(); } catch (Exception e) { LOG.e("CommonUtil:getSDCardPath", e.toString()); return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }
通過執行命令獲得mounts文件(存留在內存中的文件)中的信息,來取出外置SDcard的路徑。
