当 Android 版本为 4.4+ 时,我的应用程序必须检查某个文件夹是否在辅助存储上。
我正在使用这个:
private boolean isPathOnSecondaryStorage(String path) {
boolean res=false;
String secondaryStorage=System.getenv("SECONDARY_STORAGE");
String[] secondaryPaths=secondaryStorage.split(":");
for (int i=0;i<secondaryPaths.length;i++) {
String secondaryPath=secondaryPaths[i].trim();
if (path.contains(secondaryPath)) {
res=true;
}
}
return res;
}
注意:
路径由用户通过文件选择器 Activity 选择,从/mnt 开始
应用想像往常一样检查挂载的内容,例如在其插槽中插入外部 SD 卡时
所以我问上面提到的代码是否总是能够检测路径何时在辅助存储上,或者在某些设备上它可以找到不同于/mnt (Android 4.4+) 的奇怪安装点。
最佳答案
这是我目前的解决方案。不理想,但应该可以。
/**
* Uses the Environmental variable "SECONDARY_STORAGE" to locate a removable micro sdcard
*
* @return the primary secondary storage directory or
* {@code null} if there is no removable storage
*/
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;
}
/**
* Checks if a file is on the removable SD card.
*
* @see {@link Environment#isExternalStorageRemovable()}
* @param file a {@link File}
* @return {@code true} if file is on a removable micro SD card, {@code false} otherwise
*/
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;
}
关于安卓 4.4+ : check if path is on secondary storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25261178/