Android判断是否挂载外置sd卡

来源:互联网 发布:网络节点半径 编辑:程序博客网 时间:2024/06/05 10:12
  最近程序中需要查看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;    }
 

                                             
1 0
原创粉丝点击