最近做項目有獲取手機存儲和內(nèi)存的需求,查了各種方法都不太如人意,手機存儲倒是能正常獲取,但是獲取SD卡的時候卻總是有路徑、權(quán)限等各種各樣的問題。后來多方查詢終于找到了一篇博客,用了一下還挺滿足需求的。放上鏈接:
以下是原文方法:
核心是先獲取內(nèi)存管理器,然后用invoke獲取所有路徑,再根據(jù)是否可移除(SD卡可移除,內(nèi)存不行)獲取到不同的路徑。具體方法如下:
/**
* 通過反射調(diào)用獲取內(nèi)置存儲和外置sd卡根路徑(通用)
*
* @param mContext 上下文
* @param is_removale 是否可移除,false返回內(nèi)部存儲,true返回
外置sd卡
* @return
*/
private static String getStoragePath(Context mContext, boolean
is_removale) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removale == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}