自android3.1以后android增加了操作USB设备的API。 官网地址:http://developer.android.com/guide/topics/connectivity/usb/host.html
网上也有很多这方面的文章,不过多数是介绍如何得到设备和获取权限的,很少有介绍如何读写数据的。
最近也研究了在android下如何读写USB设备,和大家分享一下。
关于如何监听设备插拔以及获取设备权限我就不说了,大家可以在网上搜一下有很多这方面的文章,我这里就说一下如何读写数据。
UsbInterface usbInterface = usbDevice.getInterface(0);
//USBEndpoint为读写数据所需的节点
UsbEndpoint inEndpoint = usbInterface.getEndpoint(0); //读数据节点
UsbEndpoint outEndpoint = usbInterface.getEndpoint(1); //写数据节点
UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
connection.claimInterface(usbInterface, true);
//发送数据
byte[] byte2 = new byte[64];
int out = connection.bulkTransfer(outEndpoint, cmd, cmd.length, 3000);
//读取数据1 两种方法读取数据
int ret = connection.bulkTransfer(inEndpoint, byte2, byte2.length, 3000);
Log.e("ret", "ret:"+ret);
for(Byte byte1 : byte2){
System.err.println(byte1);
}
//读取数据2
/*int outMax = outEndpoint.getMaxPacketSize();
int inMax = inEndpoint.getMaxPacketSize();
ByteBuffer byteBuffer = ByteBuffer.allocate(inMax);
UsbRequest usbRequest = new UsbRequest();
usbRequest.initialize(connection, inEndpoint);
usbRequest.queue(byteBuffer, inMax);
if(connection.requestWait() == usbRequest){
byte[] retData = byteBuffer.array();
for(Byte byte1 : retData){
System.err.println(byte1);
}
}*/
然后使用connection.bulkTransfer(endpoint, buffer, length, timeout) 发送数据。
我这里读数据的时候有两种方法,读数据1和读数据2
注意:写数据时传入的是写数据节点OutEndpoint,读数据时传入的是读数据节点InEndpoint。
代码下载:http://download.csdn.net/detail/centralperk/5743323