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

你可能感兴趣的:(android,usb)