您的位置:首页 > 产品设计 > UI/UE

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

2015-06-07 01:05 447 查看
做毕设,安卓开发,用到手机蓝牙和单片机的通讯。在使用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;
}
}
}


分裂问题最终我还是选择了自己设计协议包。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息