【问题标题】:InputStream read buffer is split into two buffersInputStream 读取缓冲区被拆分为两个缓冲区
【发布时间】:2013-01-24 11:04:14
【问题描述】:

我在我的应用程序中使用了 BluetoothChat 示例和 this。我向蓝牙 SPP 设备(蓝牙到 UART)发送了一个命令并得到了答案。此答案的大小可变,但小于 255 字节。

问题是我把答案分成了两个缓冲区。第一次读取时的前几个字节(大部分只有两个),然后是其余的。我没有丢失数据,但我需要它完整才能使用它。我用mmInStream.available();(见代码片段)试过了,但这太慢了。我也用sleep(10); 尝试过,但没有用。 我能做些什么? 提前非常感谢!

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        Log.d(TAG, "create ConnectedThread: " + socketType);
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[255];
        int bytes;
        // Keep listening to the InputStream while connected
        while (true) {
            try {

                // That was a try, but it's to slow
                //bytesAv = mmInStream.available();
                //if (bytesAv>0){ 

                // Read from the InputStream
                bytes = mmInStream.read(buffer); // TODO

                byte[] buffer2 = new byte[bytes];

                System.arraycopy(buffer, 0, buffer2, 0, bytes);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer2)
                        .sendToTarget();
                //}
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothChatService.this.start();
                break;
            }
        }


    }

【问题讨论】:

    标签: android bluetooth inputstream


    【解决方案1】:

    这就是蓝牙 SPP 配置文件的本质,它不提供任何帧边界。 因此,您的应用程序应读取所有数据并使用您应通过 SPP 添加到数据中的一些附加标头重新构造任何帧。

    【讨论】:

    • 有没有办法使用 brodcastReceivers 或其他任何东西?因为 Android App 是 Master,所以我总是知道在我的请求之后我必须阅读。
    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2012-03-15
    相关资源
    最近更新 更多