2012-04-25 47 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; 
      } 
     } 

    }