您的位置:首页 > 移动开发 > Android开发

Android判断是否挂载外置sd卡

2016-04-13 22:34 489 查看
  最近程序中需要查看sd卡是否挂载,在网上看到有用Environment.MEDIA_MOUNTED来判断是否有sd卡,但实际上Environment.getExternalStorageState()得到的手机内置sd卡的状态。这里有一种方法查看外置sd卡,使用StorageVolume类,这里需要通过反射实现。StorageManager调用getVolumeList方法返回StorageVolume对象StorageVolume对象保存着卷信息,StorageVolume的isRemovable判断是否可以卸载,如果可以卸载则是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;
}
 


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: