安卓蓝牙开发中google例子BluetoothChat的问题

做毕设,安卓开发,用到手机蓝牙和单片机的通讯。在使用google原生的蓝牙例子


BluetoothChat时,对蓝牙通讯进程ConnectedThread中读取蓝牙接受socket中的数据,官方使用的是:

while (true) {
       try {
            // Read from the InputStrea
            bytes = mmInStream.read(buffer);
            Log.e(TAG, "byte的大小:"+bytes);
            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(Main.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 
            } catch (IOException e) {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            break;
                }
            }

在实际使用bytes = mmInStream.read(buffer);时,发现出现了两个问题:

1.每次read数据到buffer,不会一次性把单片机传过来的数据一次性读完。比如,我发送了3个字节的数据,是分两次read的,被分割成了一个字节和两个字节的数据。

2.buffer中的数据,可能会在socket中的数还没读完的时候,被覆盖,导致得到的数据不对。

针对这两种错误,在网上查了好久,发现了国外大神的解答:

while(true) {
     if mmInStream.getAvailable()>0 { 
          -your read code here-   //防止buffer的被覆盖
     }
     else SystemClock.sleep(100);   //解决数据被分段的问题
}

然而事实上,真正解决数据被分段的方式还是自己设计数据包,设计包头包尾自己进行判断。延时等待的方式并不算太靠谱。

单纯的解决buffer被覆盖的问题,更详细的解答,也是我最终采用的方案为:

public void run() {        
    int bytes; // bytes returned from read()
    int availableBytes = 0;        
    // Keep listening to the InputStream until an exception occurs
    while (ture) {
        try {
            availableBytes = mmInStream.available();
            if(availableBytes > 0){
                byte[] buffer = new byte[availableBytes];  
                // buffer store for the stream
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                Log.d("mmInStream.read(buffer);", new String(buffer));
                if( bytes > 0 ){                        
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();                     
                }                                   
            }
        } catch (IOException e) {
            Log.d("Error reading", e.getMessage());
            e.printStackTrace();
            break;
        }
    }
}

分裂问题最终我还是选择了自己设计协议包。。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值