App接收下位机发送过来的数据,数据格式是16进制,比方说我要发送65 -24 -4 -42 66 39 39 -16这个序列.但是接收端出现了问题,
在接收蓝牙数据的线程里我不停他的接收数据,当接收到数据的时候我就向MainActivity发送一个Message,我把接收到的数据存放在Bundle里边,然后在MainActivity中有一个Handler来处理我的Message,把数据读取出来,但是读取出来的数据顺序是乱的,而且好像读取了两次,因为我一次只读取8个字节。
下面是关键部分的代码:
while (true)
{
try {
bytes = mmInStream.read(buffer);
Message msg = mHandler.obtainMessage();
msg.what = MainActivity.MESSAGE_READ;
Bundle bundle = new Bundle();
bundle.putByteArray("info", buffer);
msg.setData(bundle);
mHandler.sendMessage(msg);
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
MainActivtiy:
case MESSAGE_READ:
Bundle bundle=msg.getData();
byte[] array=bundle.getByteArray("info");
for (int i=0;i<array.length;i++){
System.out.println(array[i]);
}
输出的结果是这样的:
10-24 17:07:46.151 21591-21591/com.example.lsj.bluetoothtest I/System.out: 66
10-24 17:07:46.151 21591-21591/com.example.lsj.bluetoothtest I/System.out: 39
10-24 17:07:46.151 21591-21591/com.example.lsj.bluetoothtest I/System.out: -16
10-24 17:07:46.161 21591-21591/com.example.lsj.bluetoothtest I/System.out: 65
10-24 17:07:46.161 21591-21591/com.example.lsj.bluetoothtest I/System.out: -24
10-24 17:07:46.161 21591-21591/com.example.lsj.bluetoothtest I/System.out: -4
10-24 17:07:46.171 21591-21591/com.example.lsj.bluetoothtest I/System.out: -42
10-24 17:07:46.171 21591-21591/com.example.lsj.bluetoothtest I/System.out: -42
10-24 17:07:46.241 21591-21591/com.example.lsj.bluetoothtest I/System.out: 39
10-24 17:07:46.241 21591-21591/com.example.lsj.bluetoothtest I/System.out: 39
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: -16
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: 65
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: -24
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: -4
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: -42
10-24 17:07:46.251 21591-21591/com.example.lsj.bluetoothtest I/System.out: -42
完全乱了。。。
首先确定不是大小端的问题