我写过一个可以从蓝牙串口接收文本的课程,但是当我发送“akkkkk”给它“tokkk”后,我发送了“a”它,为什么它的结果会被考虑?我应该怎么做才能让它“干脆”?我可以清除缓冲区,以及如何清除缓冲区?
这是我的代码:
class RecieveThread extends Thread {
private final InputStream mmInStream;
@TargetApi(Build.VERSION_CODES.ECLAIR)
protected RecieveThread(BluetoothSocket socket) {
InputStream tmpIn = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException ignored) { }
mmInStream = tmpIn;
}
public void run() {
Looper.prepare();
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String str = new String(buffer);
handler.obtainMessage(READ, bytes, -1, str)
.sendToTarget();
} catch (Exception e) {
s=e.getMessage();
System.out.print(s);
h=false;
break;
}
}
Looper.loop();
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==READ) {
String str = (String)msg.obj;
Toast.makeText(MyService.this,msg.str+"",Toast.LENGTH_SHORT).show();
}
else if(h==false)
Toast.makeText(MyService.this,"Failed:"+s+".",Toast.LENGTH_SHORT).show();
}
};
答案 0 :(得分:1)
bytes = mmInStream.read(buffer);
String str = new String(buffer);
常见问题。你忽略了计数。
bytes = mmInStream.read(buffer);
String str = new String(buffer, 0, bytes);