android 蓝牙发送和接收有冲突
我的app设计为
1.向主机发送开始命令
2蓝牙循环接收从主机发送的数据
问题:接收到的数据中第一位数据有时候会是发送命令的第一位
比如:我发送“UP”给主机 正常接收数据为“123456” 异常情况就会出现“D123456”
不知道是为什么
代码如下:
这里是发送命令“UP”
ScanButton.setOnTouchListener(new Button.OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
String message;
byte[] msgBuffer;
int action = event.getAction();
switch(action)
{
case MotionEvent.ACTION_UP:
try {
os = _socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}
message = "UP\n";
msgBuffer = message.getBytes();
try {
os.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;
}
return false;
}
});
这里是接收
Thread ReadThread = new Thread() {
public void run() {
int num = 0;
int i=0;
int TotalNum = 0;
byte[] buffer = new byte[150];
bRun = true;
// 接收线程
while (true) {
try {
while (is.available() == 0) {
while (bRun == false) {
}
}
while (true) {
num = is.read(buffer); // 读入数据buffer 打印出来不对 必须转换为其它类型才能打印查看
String s = new String(buffer, 0, num);
smsg += s; // 写入接收缓存
TotalNum += num;
if(TotalNum >= 100){
byte[] data = smsg.getBytes();
for(i = 0; i < 50; i++){
ImageY[i] = data[count++];
ImageX[i] = data[count++];
}
TotalNum = 0;
smsg="";
break;
}
}
handler.sendMessage(handler.obtainMessage());// 发送显示消息,进行显示刷新
} catch (IOException e) {
}
}
}
};