2012-04-25 130 views
1

我想通过bulkTransfer发送一个简短的数据包(只有2个字符)到通过USB连接的摄像头。我将Samsung Galaxy S2与Android 4.0.3用作主机。一切似乎都很好,接受...没有数据实际上正在发送。理论上,bulkTransfer方法返回一个正值,这意味着数据已被传输,但没有可见的效果。代码如下:不成功bulkTransfer - Android 4.0.3

 char ch = (char)34; 
    char[] record = {'P',ch}; 
    String r = record.toString(); 
    byte[] bytes = r.getBytes(Charset.forName("ASCII")); 
    int TIMEOUT = 10000; 
    boolean forceClaim = true; 
    UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); 
    UsbInterface intf = device.getInterface(0); 
    for (int i = 0; i < intf.getEndpointCount(); i++) { 
      UsbEndpoint ep = intf.getEndpoint(i); 
      if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { 
      if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { 
       endpoint = ep; 
       //Integer dir = endpoint.getDirection(); 
       UsbDeviceConnection connection = mUsbManager.openDevice(device); 
       if(connection!=null){devMessage+=" I connected";} 
       connection.claimInterface(intf, forceClaim); 
       Integer res = connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); 
       if (res>0){devMessage += "some data transfered.";} 
       connection.releaseInterface(intf); 
      break; 

      } 
      } 

在启动bulkTransfer之前还有什么需要添加的东西吗?在我开始bulkTransfer之前是否需要controlTransfer?还有什么我可能会忘记的。 请理解,因为这是我的第一款使用USB通信的应用程序,网络上的资源并不多。我已经阅读了有关usb主机在developer.android上的所有信息...所以请不要直接指向我。非常感谢您的帮助。

回答

0

可能是接口不正确您使用device.getInterface(0)。所以这可能是不对的。试试这个来获得界面。

for (int i = 0; i < device.getInterfaceCount(); i++) { 
     UsbInterface usbif = device.getInterface(i); 

     UsbEndpoint tOut = null; 
     UsbEndpoint tIn = null; 

     int tEndpointCnt = usbif.getEndpointCount(); 
     if (tEndpointCnt >= 2) { 
      for (int j = 0; j < tEndpointCnt; j++) { 
       if (usbif.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { 
        if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT) { 
         tOut = usbif.getEndpoint(j); 
        } else if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN) { 
         tIn = usbif.getEndpoint(j); 
        } 
       } 
      } 

      if (tOut != null && tIn != null) { 
       // This interface have both USB_DIR_OUT 
       // and USB_DIR_IN of USB_ENDPOINT_XFER_BULK 
       usbInterface = usbif; 
       endpointOut = tOut; 
       endpointIn = tIn; 
      } 
     } 

    }