如何在Android API Level 11中获取SD卡目录?这段代码
Environment.getExternalStorageDirectory();
返回手机记忆库目录(内部目录)。我仅为外部存储添加了AndroidManifest.xml
的权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在某些手机上,此代码可以正常工作(例如,ZTE Blade HN和Phillips),e.t。具体回归SD卡路径。但联想返回内部路径。每部手机都有正式恢复。
答案 0 :(得分:0)
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
原始方法经过测试并使用我的手机
答案 1 :(得分:0)
在某些设备中,外部SD卡默认名称显示为extSdCard,而其他设备则显示为sdcard1。这段代码片段有助于找出确切的路径,并有助于您重温外部设备的路径,就像手机连接笔记本电脑一样。
private String[] getPaths()
{
String[] paths = new String[4];
if(new File("/storage/extSdCard/").exists())
paths[0]="/storage/extSdCard/";
if(new File("/storage/sdcard1/").exists())
paths[1]="/storage/sdcard1/";
if(new File("/storage/usbcard1/").exists())
paths[2]="/storage/usbcard1/";
if(new File("/storage/sdcard0/").exists())
paths[3]="/storage/sdcard0/";
return paths;
}