[英]Bundling inputStream.read messages
我正在使用Android蓝牙聊天示例代码与蓝牙设备聊天(发送命令+接收响应)。 当我发送命令时,它工作正常,并且收到了从设备传递到消息处理程序的响应。 我遇到的问题是响应被分成几部分。
例:
我发送了字符串"{Lights:ON}\\n"
,我的活动正确显示了Me: {Lights:ON}
。 设备指示灯亮起,并返回响应"{FLash_Lights:ON}\\n"
。 但是,我的活动显示DeviceName: {Fla
,换行, DeviceName: sh_Lights:ON}
(或某些变化形式)。
现在,我是线程和蓝牙的新手,但我已将问题归结为连接的线程类(在bluetoothchatservice中),更具体地说是侦听传入字节的public void run()
。
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[9000];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothThreading.this.start();
break;
}
}
}
我了解这是为了侦听传入的任何字节(作为聊天服务)。 但是我确切地知道我正在写的设备,我知道我应该收到的响应, 我想做的是在将此响应发送回mHandler之前将其打包。
任何帮助将是惊人的! 谢谢!
注意 :我知道使用此示例作为向设备发送命令并接收响应的方法有点过大(特别是因为我确切知道我要发送的内容,之后需要直接接收)。 指出您可能还知道的任何简化样本,将是非常棒的。 在一天结束时,我只需要搜索,连接到设备,按下按钮即可将byte []发送到设备,接收byte []响应,打印并存储它。
“ read()”正在阻止调用,并在通过蓝牙接收到少量字节时返回。 “很少”的计数不是固定的,这就是传入响应似乎被分解成碎片的原因。 因此,要获取完整的响应,必须将所有这些部分连接在一起。
在响应流以特定字符终止的情况下,随后的代码逻辑可以累加在终止字符之前到达的字节。 并且一旦检测到终止字符,则将累积的响应发送到主要活动。 (请注意,在下面的代码段中,使用的终止字符为0x0a)。
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[9000];
int bytes;
ByteArrayOutputStream btInStream = new ByteArrayOutputStream( );
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
btInStream.write(Arrays.copyOf(buffer, bytes) );
if (buffer[bytes - 1] == 0x0a){
mHandler.obtainMessage(MainActivity.MESSAGE_READ, btInStream.size(), 0,btInStream.toByteArray());
.sendToTarget();
btInStream.reset();
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothThreading.this.start();
break;
}
}
}
还要注意,代码未经测试,但被提议作为解决问题中提到的问题的一种方法。 可能需要在几个地方进行更正。 请测试并告知结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.