如何清除缓冲区?
How can I clear the buffer?
我写了一个class可以从蓝牙串口接收文本,但是当我发送“a”它发送“kkkk”后它吐“akkk”它吐“kkkk”,为什么要结果超出了考虑?我应该怎么做才能让它吐“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();
}
};
bytes = mmInStream.read(buffer);
String str = new String(buffer);
常见问题。你忽略了计数。
bytes = mmInStream.read(buffer);
String str = new String(buffer, 0, bytes);
我写了一个class可以从蓝牙串口接收文本,但是当我发送“a”它发送“kkkk”后它吐“akkk”它吐“kkkk”,为什么要结果超出了考虑?我应该怎么做才能让它吐“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();
}
};
bytes = mmInStream.read(buffer);
String str = new String(buffer);
常见问题。你忽略了计数。
bytes = mmInStream.read(buffer);
String str = new String(buffer, 0, bytes);