【发布时间】:2013-08-10 07:03:17
【问题描述】:
在 bluetoothChat 示例应用程序中,发送和接收的数据被添加到名为 mConversationArrayAdapter 的 ArrayAdapter 中。在那里,每个字符都被添加到数组中。
在我的例子中,我有一个字符串而不是一个数组,因为我不需要发送和接收几个数据,我只需要发送一个字符串,每次接收一个字符串。
我遇到的问题是,如果我首先收到一个像hello world 这样的字符串,然后收到一个较短的字符串,第一个会被第二个覆盖,而不是删除第一个并写入新的。
所以,如果我先收到hello world,然后我想我必须收到bye,我真正收到的是byelo world。
那么,如何在每次收到我想要的内容时清除缓冲区?
代码片段
发送数据:
byte[] send1 = message_full1.getBytes();
GlobalVar.mTransmission.write(send1);
写调用:
public void write(byte[] out) {
/**Create temporary object*/
ConnectedThread r;
/**Synchronize a copy of the ConnectedThread*/
synchronized (this) {
if (GlobalVar.mState != GlobalVar.STATE_CONNECTED) return;
r = GlobalVar.mConnectedThread;
}
/**Perform the write unsynchronized*/
r.write(out);
}
写线程:
public void write(byte[] buffer) {
try {
GlobalVar.mmOutStream.write(buffer);
/**Share the sent message back to the UI Activity*/
GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {}
}
最后,阅读线程:
public void run() {
byte[] buffer = new byte[12]; // buffer store for the stream
int bytes; // bytes returned from read()
/**Keep listening to the InputStream until an exception occurs*/
while (true) {
try {
/**Read from the InputStream*/
bytes = GlobalVar.mmInStream.read(buffer);
/**Send the obtained bytes to the UI activity*/
GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
GlobalVar.mTransmission.connectionLost();
/**Start the service over to restart listening mode*/
//GlobalVar.mTransmission.start();
break;
}
}
}
【问题讨论】:
-
贴出相关代码sn-ps...
-
@Sw4Tish,发布代码
标签: android string bluetooth buffer