android - 如何清除蓝牙输入流缓冲区

标签 android string bluetooth buffer

在 bluetoothChat 示例应用程序中,发送和接收的数据被添加到名为 mConversationArrayAdapter 的 ArrayAdapter 中。在那里,每个字符都被添加到数组中。

在我的例子中,我有一个字符串而不是一个数组,因为我不需要发送和接收多个数据,我只需要发送一个字符串,每次接收一个字符串。

我遇到的问题是,如果我第一次收到像 hello world 这样的字符串,然后我收到一个较短的字符串,第一个会被第二个覆盖,而不是删除第一个并编写新的。

所以,如果我首先收到hello world,然后我假设我必须收到bye,那么我真正收到的是byelo world.

那么,每次接收到我想要的内容时如何清除缓冲区?

代码 fragment

发送数据:

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

最佳答案

试试这个

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

关于android - 如何清除蓝牙输入流缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18128194/

相关文章:

android - 通过蓝牙连接安卓手机和笔记本电脑

java - 试图关闭 OkHttp 的响应但缺少 AutoCloseable 接口(interface)

android - 如何以编程方式在 Android 中翻转 ImageButton

android - emulator-arm.exe 已停止工作

android - React Native 中的数据更改后组件未更新

c++ - std::string SSO 调整

ios - swift 3 : Bluetooth list is empty

c - 具有字符串的结构中的 fscanf

java - 比较 vector 并选择公共(public)元素java

c# - 如何强制串行端口写入方法在发送数据之前等待线路清除?