0
我使用BluetoothChat示例和this作为我的应用程序。我发送了一个命令到蓝牙SPP设备(蓝牙到UART)并找回了答案。这个答案有一个可变的大小,但它小于255个字节。InputStream读取缓冲区被分成两个缓冲区
问题是,我回到了被分成两个缓冲区的答案。首先读取几个字节(主要是两个字节),其余部分在第一次读取之后。我没有丢失数据,但我需要它完整地使用它。我尝试了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;
}
}
}
有没有办法使用brodcastReceivers或其他东西?因为Android应用程序是主人,所以我总是知道我必须在我的请求后阅读。 – user1390816