判断U盘是否挂载和获取U盘路径

判断U盘是否挂载和获取U盘路径

正常可以通过广播来监听U盘的挂载状态,如果刚开机未收到开机广播就需要获取U盘状态

1.判断U盘是否挂载

public static boolean getUsb(StorageManager storageManager) {
        try {
            Class<?> cls = Class.forName("android.os.storage.VolumeInfo");
            cls.getMethod("getDescriptionComparator", new Class[0]);
            Method method = StorageManager.class.getMethod("getBestVolumeDescription", cls);
            Method method2 = StorageManager.class.getMethod("getVolumes", new Class[0]);
            Method method3 = cls.getMethod("isMountedReadable", new Class[0]);
            Method method4 = cls.getMethod("getType", new Class[0]);
            Method method5 = cls.getMethod("getPath", new Class[0]);
            for (Object obj : (List) method2.invoke(storageManager, new Object[0])) {
                if (obj != null && ((Boolean) method3.invoke(obj, new Object[0])).booleanValue() && ((Integer) method4.invoke(obj, new Object[0])).intValue() == 0) {
                    String path = ((File) method5.invoke(obj, new Object[0])).getPath();
                    Log.d(TAG, "-----------path1-----------------" + ((String) method.invoke(storageManager, obj)));
                    Log.d(TAG, "-----------path2 @@@@@-----------------" + path);
                    if (path != null && !"".equals(path)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

2.广播监听U盘状态

 public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action != null) {
            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                Log.e(TAG, "USB=MOUNTED");
                handler.sendEmptyMessage(StatusConstant.Usb.MOUNTED);
            } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
                Log.e(TAG, "USB=UNMOUNTED");
                handler.sendEmptyMessage(StatusConstant.Usb.UNMOUNTED);
            }
        }
    }

3.获取U盘路径

ArrayList<String> usbPathList = new ArrayList<String>();
        usbCount = 0;
        StorageManager sm = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);
        for (StorageVolume volume : sm.getVolumeList()) {
            if ((!volume.getPath().contains("emulated")) && volume.getState().equals("mounted")) {
                usbPathList.add(volume.getPath());
                usbCount++;
                continue;
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值