我使用了 BluetoothChat 示例,并将其用于我的应用程序。我向蓝牙 SPP 设备(蓝牙到 UART)发送了一个命令并得到了答案。此答案的大小可变,但小于 255 字节。
问题是我得到了分成两个缓冲区的答案。第一次读取时的前几个字节(大部分只有两个),然后是其余的。我没有丢失数据,但我需要它完整才能使用它。我试过了mmInStream.available();
(见代码片段),但这太慢了。我也用 a 试过,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;
}
}
}