Android-获取外置SDcard路径

时间:2023-03-09 16:30:41
Android-获取外置SDcard路径

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的路径。

本文转自:http://my.eoe.cn/1028320/archive/4718.html