Android獲取外接SD卡讀寫路徑
阿新 • • 發佈:2018-12-01
1. 外接SD卡的一些問題
1.1 關於外接SD卡上的讀寫路徑
Android 4.4
及以上版本,應用的外接SD卡讀寫路徑被限定在固定路徑上(外接SD卡根路徑/Android/data/包名/files
)。
Android4.4
以下版本,申請了外接SD卡讀寫許可權的應用在整個外接SD卡上都有讀寫許可權。
1.2 關於外接SD卡路徑
另外Android沒有提供獲取外接SD卡路徑的API(getExternalStorageDirectory()
獲取的實際是內建SD卡路徑)。
2. 獲取應用在外接SD卡讀寫根路徑
在Android 4.4
以下版本,獲取的應該是外接SD卡的根目錄(類似/storage/sdcard1
Android 4.4
及以上版本,獲取的是應用在SD卡上的限定目錄(外接SD卡根路徑/Android/data/包名/files/file
)
程式碼如下:
public static String getExternalSDPath(Context aContext) {
String root = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
root = getExternalSDPathKITKAT(aContext);
File f = new File(root);
if (!f.exists()) {
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
if (!f.exists()) {
root = null;
}
}
} else {
root = getExternalSDCardPath(aContext);
}
return root;
}
// Android 4.4及以上版本,獲取軟體在外接SD卡上的儲存路徑
public static String getExternalSDPathKITKAT(Context aContext) {
String rootPath = getStoragePath(aContext, true);
if (TextUtils.isEmpty(rootPath)) {
return null;
}
File f = new File(rootPath, "Android/data/" + aContext.getPackageName() + "/files/file");
String fpath = f.getAbsolutePath();
return fpath;
}
// Android 4.4 以下版本獲取外接SD卡根目錄
public static String getExternalSDCardPath(Context aContext) {
HashSet<String> paths = getExternalMounts();
File defaultPathFile = aContext.getExternalFilesDir(null);
String defaultPath;
if (defaultPathFile == null) {
return null;
} else {
defaultPath = defaultPathFile.getAbsolutePath();
}
String prefered = null;
for (Iterator it = paths.iterator(); it.hasNext();) {
String path = (String) (it.next());
if (prefered == null && !defaultPath.startsWith(path)) {
prefered = path;
}
}
return prefered;
}