StorageManager获取U盘挂载状态

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();
                }

            }
        }
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值