0

我有两部安卓手机,都是安卓6.0。我希望他们通过 USB 相互通信。我有一根 OTG USB 数据线,可以将一部手机插入另一部手机。一个是usb主机,另一个是配件。

我的代码基于以下教程:

现在

  1. 主机和附件可以连接
    根据这个项目:https
    ://github.com/quandoo/android2android-accessory 主机发送控制消息:
    private void initStringControlTransfer(final UsbDeviceConnection deviceConnection, final int index, final String string) { deviceConnection.controlTransfer(0x40, 52, 0, index, string.getBytes(), string.length(), USB_TIMEOUT_IN_MS); } initStringControlTransfer(connection, 0, "UsbTest Example"); // MANUFACTURER initStringControlTransfer(connection, 1, "UsbTest"); // MODEL initStringControlTransfer(connection, 2, "Test Usb Host and Accessory"); // DESCRIPTION initStringControlTransfer(connection, 3, "0.1"); // VERSION initStringControlTransfer(connection, 4, ""); // URI initStringControlTransfer(connection, 5, "42"); // SERIAL connection.controlTransfer(0x40, 53, 0, 0, new byte[]{}, 0, USB_TIMEOUT_IN_MS);
  2. 主机可以使用 UsbRequest 从附件接收数据
    主机代码
    UsbRequest request = new UsbRequest(); request.initialize(mConnection, mEndIn); boolean ret = request.queue(buffer, BUFFER_SIZE_IN_BYTES); if (ret) { if (mConnection.requestWait() == request) { // Succeed } }
    附件代码
    try { mOutStream.write(sendBuff); mOutStream.flush(); } catch (IOException e) { }
  3. 配件无法接收数据
    主机代码
    int len = mInStream.read(msg); // block here, read never return if (len > 0) { // succeed }
    配件代码
    UsbRequest request = new UsbRequest(); request.initialize(mConnection, mEndOut); ByteBuffer buffer = ByteBuffer.wrap(text.getBytes()); boolean ret = request.queue(buffer, text.getBytes().length); if (ret) { // request.queue succeed } // if I use bulkTransfer, it always return a negative value //int len = mConnection.bulkTransfer(mEndOut, text.getBytes(), text.getBytes().length, USB_TIMEOUT_IN_MS); //if (len < 0) { // // always run here //} else { //
    //}

有人知道吗?

4

0 回答 0