在项目中遇到这个问题,因为Android4.4Kitkat的新特性,导致不能对外置SD卡的文件夹进行写入操作,然后因为写入操作导致程序崩溃。
这个问题着实困扰了我好久,解决这个问题主要是两个方向,第一判断这个存储路径是否是可以写入的。第二,判断是不是android4.4的设备,如果是再判断相应存储的路径是不是外置SD卡路径,这时就需要解决获取外置SD卡路径的问题了。因为第一个方向没行得通,所以本文主要介绍的是获取外置SD卡路径的方法。
public static File getRemovableStorage() {
final String value = System.getenv("SECONDARY_STORAGE");
if (!TextUtils.isEmpty(value)) {
final String[] paths = value.split(":");
for (String path : paths) {
File file = new File(path);
if (file.isDirectory()) {
return file;
}
}
}
return null;
}
public static boolean isFileOnRemovableStorage(File file) {
final File microSD = getRemovableStorage();
if (microSD != null) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
if (canonicalPath.startsWith(microSD.getAbsolutePath())) {
return true;
}
} catch (IOException e) {
}
}
return false;
}
以上代码参考如下link:
http://stackoverflow.com/questions/25261178/android-4-4-check-if-path-is-on-secondary-storage
其他解决办法参考如下:
http://stackoverflow.com/questions/11281010/how-can-i-get-external-sd-card-path-for-android-4-0/19831522#19831522