Android蓝牙读取数据的问题

平凡的L同学
博客专家认证
2016-10-24 05:11:50
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
完全乱了。。。
首先确定不是大小端的问题
...全文
137 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
平凡的L同学 2016-10-24
  • 打赏
  • 举报
回复
buffer占8个字节

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧