StorageManager是Android SDK中管理存储设备的一个类。其中的存储设备分内部存储和外部存储,外部存储可以有SDCard、U盘等其他挂载的外设。
StorageVolume代表的是一个设备信息的数据结构,里面包含了名称、路径、挂载状态等等信息。
以前获取设备列表的方法大多是通过反射获getVolumeList()方法获取到StorageVolume[]数组,但是现在发现完全没有必要的,通过getStorageVolumes()方法便可以获取到StorageVolume的集合。只是在取StorageVolume里面的字段的时候,像Path、ID这些属性的get方法是隐藏的,需要使用反射来获取。示例代码如下:

 mStorageManager = getSystemService(StorageManager.class);
        List<StorageVolume> volumeList = mStorageManager.getStorageVolumes();
        for (StorageVolume volume : volumeList) {
            if (null != volume && volume.isRemovable()) {
                String label = volume.getDescription(this);   //这个其实就是U盘的名称
                String status = volume.getState();                   //设备挂载的状态,如:mounted、unmounted
                boolean isEmulated = volume.isEmulated();            //是否是内部存储设备
                boolean isRemovable = volume.isRemovable();          //是否是可移除的外部存储设备
                String mPath="";                                     //设备的路径


                try {
                    Class myclass = Class.forName(volume.getClass().getName());
                    Method getPath =  myclass.getDeclaredMethod("getPath",null);
                    getPath.setAccessible(true);
                    mPath = (String) getPath.invoke(volume);

                    Log.i(TAG,"name:"+label);
                    Log.i(TAG,"status:"+status);
                    Log.i(TAG,"isEmulated:"+isEmulated);
                    Log.i(TAG,"isRemovable:"+isRemovable);
                    Log.i(TAG,"mPath:"+mPath);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }catch (InvocationTargetException e) {
                    e.printStackTrace();
                }catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐