https://blog.csdn.net/kevinliu1987/article/details/51147552
最近程序中需要查看sd卡是否挂载,在网上看到有用Environment.MEDIA_MOUNTED来判断是否有sd卡,但实际上Environment.getExternalStorageState()得到的手机内置sd卡的状态。这里有一种方法查看外置sd卡,使用StorageVolume类,这里需要通过反射实现。StorageManager调用getVolumeList方法返回StorageVolume对象StorageVolume对象保存着卷信息,StorageVolume的isRemovable判断是否可以卸载,如果可以卸载则是sd卡。代码如下:
/**
* 判断外置sd卡是否挂载
*
*/
private boolean isSDMounted() {
boolean isMounted = false;
StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
try {
Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);
getVolumList.setAccessible(true);
Object[] results = (Object[])getVolumList.invoke(sm, null);
if (results != null) {
for (Object result : results) {
Method mRemoveable = result.getClass().getMethod("isRemovable", null);
Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);
if (isRemovable) {
Method getPath = result.getClass().getMethod("getPath", null);
String path = (String) mRemoveable.invoke(result, null);
Method getState = sm.getClass().getMethod("getVolumeState", String.class);
String state = (String)getState.invoke(sm, path);
if (state.equals(Environment.MEDIA_MOUNTED)) {
isMounted = true;
break;
}
}
}
}
} catch (NoSuchMethodException e){
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return isMounted;
}