私は 2 台の Android スマートフォンを持っていますが、どちらも Android 6.0 です。USB経由で相互に通信したい。ある電話機を別の電話機に接続する OTG USB ケーブルがあります。1 つは USB ホスト、もう 1 つはアクセサリです。
私のコードは、次のチュートリアルに基づいています。
- http://developer.android.com/guide/topics/connectivity/usb/host.html
- http://developer.android.com/guide/topics/connectivity/usb/accessory.html
今
- ホストとアクセサリは
、このプロジェクトによると接続できます: 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);
- ホストは、アクセサリの使用からデータを受信できます 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) { }
- アクセサリはデータを受信できません
ホスト コード
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 { //
//}
誰もこれについて知っていますか?