关于Android与USB设备的连接,所能搜索到的资料特别的少,但恰恰接到了一个这样的需求,使用android平板通过USB与一个外接设备进行通讯,这个设备是一个压力感应器,在压力发生变化时可以测到相应的压力值,Android设备通过USB对设备进行供电并与该设备进行通讯,将测量到的数据读取下来并进行保存分析。这是一个典型的Android设备作为USBHost、外接设备作为USBDevice的Host Mode。关于Android所提供的USB连接模式,可以参考:http://developer.android.com/guide/topics/connectivity/usb/index.html,这里对两种连接模式都做了比较详细的介绍,不再赘述。下面主要针对我所遇到的问题做一些分析。
首先看Host mode所需要用的的类:
UsbManager:Allows you to enumerate and communicate with connected USB devices.字面含义就是允许你列举并与已连接的USB设备进行交互,其实就是一个USB管理器,可以通过它来获取已连接的USB Device列表。使用上很简单:UsbManager manager = (UsbManager) getSystemService(USB_SERVICE);就可以获取到一个实例。
USBDevice:Represents a connected USB device and contains methods to access its identifying information, interfaces, and endpoints.表示一个已连接的USB设备,包含获取它的识别信息、接口和端点的方法。获取一个USBDevice列表的方法:HashMap<String, UsbDevice> devices = um.getDeviceList();。
UsbInterface:Represents an interface of a USB device, which defines a set of functionality for the device. A device can have one or more interfaces on which to communicate on.表示一个为该设备定义了一个函数集的USB设备接口。一个设备可以拥有一个或多个用来交互的接口。获取一个设备的接口数量:int interfaceCount = device.getInterfaceCount();,如果使用index为0的interface则可以:UsbInterface ui = device.getInterface(0); 。
UsbEndpoint:Represents an interface endpoint, which is a communication channel for this interface. An interface can have one or more endpoints, and usually has input and output endpoints for two-way communication with the device. 表示一个接口端点,该端点作为这个接口的一个交互channel,一个接口可以拥有一个或多个端点,通常有输入和输出端点为一个设备提供两种交互方式。
UsbDeviceConnection:Represents