如何清空蓝牙InputStream缓冲区

4
在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;
        }
    }
}

发布相关的代码片段... - Sw4Tish
@Sw4Tish,发布了代码 - masmic
1个回答

0

试一下这个

bytes = inputStream.read(buffer);
buffer[bytes] = '\0';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接