1、添加StorageInfo.java信息类
public class StorageInfo {
public String path;
public String state;
public boolean isRemoveable;
public StorageInfo(String path) {
this.path = path;
}
public boolean isMounted() {
return "mounted".equals(state);
}
}
2、通过反射获取设备所有存储器
List<StorageInfo> storagges = new ArrayList<StorageInfo>();
StorageManager storageManager = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);
try {
Class<?>[] paramClasses = {};
Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses);
getVolumeList.setAccessible(true);
Object[] params = {};
Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params);
if(null != invokes) {
StorageInfo info = null;
for(int i=0; i<invokes.length; i++) {
Object obj = invokes[i];
Method getPath = obj.getClass().getMethod("getPath", new Class[0]);
String path = (String) getPath.invoke(obj, new Object[0]);
info = new StorageInfo(path);
File file = new File(info.path);
if ((file.exists()) && (file.isDirectory()) && (file.canWrite())) {
Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]);
String state = null;
try {
Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
state = (String) getVolumeState.invoke(storageManager, path);
info.state = state;
} catch (Exception e) {
e.printStackTrace();
}
if (info.isMounted()) {
info.isRemoveable = ((Boolean) isRemovable.invoke(obj, new Object[0])).booleanValue();
storagges.add(info);
}
}
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
如何判断存储器是内置存储还是外置存储呢?
StorageVolume这个类中提供了一个isRemovable()接口,通过反射调用它就可以知道存储器是否可以移除。把可以移除的存储器认定为外置sdcard,不可移除的存储器认定为内置存储器。
Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]);
同上面一样,需要反射系统接口才可以获取到挂载状态。下面是代码片段
Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
state = (String) getVolumeState.invoke(storageManager, info.path);
info.state = state;
总结:
通过反射系统的StorageManager以及StorageVolume类提供的接口,就可以拿到Android设备挂载的所有存储器路径,以及存储器类型(内置存储还是外置存储),还有存储器的挂载状态等信息。