所有通过USB连接android设备进行通讯的步骤都是大同小异:查询usb设备列表 ——>匹配对应的设备类型(如productid , vendorId)等——>连接usb设备,找到连接通讯的节点——>配置通讯信息,进行通讯。以上是通常的连接usb设备进行通讯的步骤和特点。
(Human Interface devices)指的是人机交互接口设备,通常是指我们日常用到的键盘鼠标等设备。
标准的USB设备总共包括五种USB描述符:设备描述符,配置描述符,接口描述符,端点描述符,字符串描述符。HID设备除了需要标准的USB描述符还需要HID报告描述符,HID物理描述符可选。HID是一种USB通信协议,无需安装驱动就能进行交互。

有些场景下,我们会用到复合usb-hid,比如在usb camera中我们需要在摄像头硬件里增加物理按键来实现相关的功能,这种情况下就会涉及到复合usb'-hid的场景,这种情况下,我们需要找到相关的接口描述符,然后进行与硬件按钮进行协议交互。
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); //找到对应的设备列表,然后与已知的productId和vendorID进行匹配找到对应的设备。 UsbDevice device = (UsbDevice) manager.getDeviceList().valuse().toArray()[0];
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Application.getBaseApp().getApplicationContext(), 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE
);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
Application.getBaseApp().getApplicationContext().registerReceiver(mUsbReceiver, filter);
manager.requestPermission(device, pendingIntent);
if (device != null) {
connection = manager.openDevice(device);
if (connection == null) {
return;
}
interfacesList = new LinkedList();
for (int i = 0; i < device.getInterfaceCount(); i++) {
UsbInterface intf = device.getInterface(i);
interfacesList.add(intf);
}
usbThreadDataReceiver = new USBThreadDataReceiver();
usbThreadDataReceiver.start();
}
//循环接收消息
for (UsbInterface intf : interfacesList) {
if (intf.getInterfaceClass() != 0x0E) { //非视频流接口描述
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint endPointRead = intf.getEndpoint(i);
connection.claimInterface(intf, true);
if (UsbConstants.USB_DIR_IN == endPointRead.getDirection()) {
while (!isStopped) {
final byte[] buffer = new byte[endPointRead.getMaxPacketSize()];
int status = connection.bulkTransfer(endPointRead, buffer, buffer.length, 100);
if (status > 0) {
if (listener != null) {
listener.recevie(bytes2HexString(buffer));
}
}
}
}