android广播监听U盘插拔以及读取文件数据

广播的action

主要用UsbManager.ACTION_USB_DEVICE_ATTACHED和UsbManager.ACTION_USB_DEVICE_DETACHED来判断

public class USBBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (action) {
            case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播
                UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device_add != null) {
                    EventBusUtil.sendEvent(new MessageEvent(1));
                }
                break;
            case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播
                //Toast.makeText(context, "拔出", Toast.LENGTH_LONG).show();
                EventBusUtil.sendEvent(new MessageEvent(0));
                break;
        }
    }
}

然后再具体的页面注册广播

IntentFilter usbDeviceStateFilter = new IntentFilter();
    usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        baseActivity.registerReceiver(usbBroadcastReceiver, usbDeviceStateFilter);

数据读取用到github上开源的一个库
implementation ‘com.github.mjdev:libaums:0.5.5’

//获取到OTG连接的U盘
    public FileSystem otgGet() {
        UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(baseActivity);
        FileSystem currentFs = null;
        for (UsbMassStorageDevice device : devices) {//一般只有一个OTG借口,所以这里只取第一个
            try {
                device.init();
                //如果设备不支持一些格式的U盘,这里会有异常
                if (device == null || device.getPartitions() == null ||
                        device.getPartitions().get(0) == null ||
                        device.getPartitions().get(0).getFileSystem() == null) {
                    return null;
                }
                currentFs = device.getPartitions().get(0).getFileSystem();
                cFolder = currentFs.getRootDirectory();
                readFromUDisk();
            } catch (Exception e) {
                return null;
            }
        }
        return currentFs;
    }

  private void readFromUDisk() {
        usbFiles = new UsbFile[0];
        try {
            usbFiles = cFolder.listFiles();
            xmlName = cFolder.list();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null != usbFiles && usbFiles.length > 0) {
            handle.sendEmptyMessage(0);
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你丶快乐吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值