android usb host 读写USB设备

自android3.1以后android增加了操作USB设备的API。 官网地址:http://developer.android.com/guide/topics/connectivity/usb/host.html

网上也有很多这方面的文章,不过多数是介绍如何得到设备和获取权限的,很少有介绍如何读写数据的。

最近也研究了在android下如何读写USB设备,和大家分享一下。

关于如何监听设备插拔以及获取设备权限我就不说了,大家可以在网上搜一下有很多这方面的文章,我这里就说一下如何读写数据。

[java]  view plain copy
  1.                      UsbInterface usbInterface = usbDevice.getInterface(0);  
  2. //USBEndpoint为读写数据所需的节点  
  3. UsbEndpoint inEndpoint = usbInterface.getEndpoint(0);  //读数据节点  
  4. UsbEndpoint outEndpoint = usbInterface.getEndpoint(1); //写数据节点  
  5. UsbDeviceConnection connection = usbManager.openDevice(usbDevice);  
  6. connection.claimInterface(usbInterface, true);  
  7.   
  8. //发送数据  
  9. byte[] byte2 = new byte[64];  
  10. int out = connection.bulkTransfer(outEndpoint, cmd, cmd.length, 3000);  
  11.   
  12. //读取数据1   两种方法读取数据  
  13. int ret = connection.bulkTransfer(inEndpoint, byte2, byte2.length, 3000);  
  14. Log.e("ret""ret:"+ret);  
  15. for(Byte byte1 : byte2){  
  16.     System.err.println(byte1);  
  17. }  
  18.   
  19. //读取数据2  
  20. /*int outMax = outEndpoint.getMaxPacketSize(); 
  21. int inMax = inEndpoint.getMaxPacketSize(); 
  22. ByteBuffer byteBuffer = ByteBuffer.allocate(inMax); 
  23. UsbRequest usbRequest = new UsbRequest(); 
  24. usbRequest.initialize(connection, inEndpoint); 
  25. usbRequest.queue(byteBuffer, inMax); 
  26. if(connection.requestWait() == usbRequest){ 
  27.     byte[] retData = byteBuffer.array(); 
  28.     for(Byte byte1 : retData){ 
  29.         System.err.println(byte1); 
  30.     } 
  31. }*/  


首先得到可以操作USB设备的节点Endpoint,0为读数据节点,1未写数据节点。

然后使用connection.bulkTransfer(endpoint, buffer, length, timeout) 发送数据。

我这里读数据的时候有两种方法,读数据1和读数据2

注意:写数据时传入的是写数据节点OutEndpoint,读数据时传入的是读数据节点InEndpoint。

代码下载:http://download.csdn.net/detail/centralperk/5743323


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值