私はBluetoothChatの例とこれをアプリケーションに使用しました。Bluetooth SPPデバイス(BluetoothからUART)にコマンドを送信し、応答を返しました。この回答のサイズは可変ですが、255バイト未満です。
問題は、2つのバッファに分割された答えを取り戻したことです。最初の読み取りで最初の数バイト(ほとんどは2バイト)、その後は残りのバイト。データを失うことはありませんでしたが、データを処理するにはデータが完全である必要があります。私はそれを試してみましたmmInStream.available();
(コードsnippsetを参照)が、これは遅すぎました。私も試してみましたsleep(10);
が、うまくいきませんでした。私に何ができる?よろしくお願いします!
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[255];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// That was a try, but it's to slow
//bytesAv = mmInStream.available();
//if (bytesAv>0){
// Read from the InputStream
bytes = mmInStream.read(buffer); // TODO
byte[] buffer2 = new byte[bytes];
System.arraycopy(buffer, 0, buffer2, 0, bytes);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer2)
.sendToTarget();
//}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
break;
}
}
}