java - Android 上通过蓝牙进行数据处理导致数据完整性不佳

标签 java android bluetooth inputstream

我正在处理通过蓝牙接收的一些二进制数据,但是,当大量数据同时传入时,我的数据流中会丢失或无效字节。我希望有人可以帮助我解决这个问题,因为我需要一些帮助以获得更一致的回应。我同意简单地“扔掉”坏数据。以下是相关方法,它们在“Connected”线程内运行:

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int num_bytes = 0;
        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                mmInStream.read(buffer, 0, 11);
                processBytes(buffer);

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

    private void processBytes(byte[] bytes) throws IOException {
        if (bytes[0] != delimiter) {
            int c;
            do {
                c = mmInStream.read();
            } while (c != delimiter && c != -1);
            if (c == -1) {
                return;
            }
        }
        /*Some processing happens here to generate the variables cellId and
                      voltage and cellId2 and voltage2
                    */
        // Send the obtained bytes to the UI Activity
        mHandler.obtainMessage(BluetoothInterface.DATA_READ,
                new DataPoint(cellId, voltage)).sendToTarget();
        // Send the obtained bytes to the UI Activity
        mHandler.obtainMessage(BluetoothInterface.DATA_READ,
                new DataPoint(cellId2, voltage2)).sendToTarget();

    }

最佳答案

我以前也遇到过这个问题。我不太确定是否通过在调用 processBytes 之前将流读入字符串对象来解决它。

关于java - Android 上通过蓝牙进行数据处理导致数据完整性不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5784567/

相关文章:

android - 找到最近的信标

java - LibGDX - Camera.update() 调用不执行任何操作

java - Servlet 从服务器加载视频文件

android - 如何解决 "The item you were attempting to purchase could not be found"

java将二进制代码保存到文件中

Android firebase user_dim.user_id==null

objective-c - 使用 String 创建一个 128 位的 UUID

java - 从扩展 Service 的类更新 MainActivity 的 TextView

java - 如何在 Java 中使用泛型转换列表?

java - 如何使我的交换机保护套在JFrame上起作用?