0

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

问题是我得到了分成两个缓冲区的答案。第一次读取时的前几个字节(大部分只有两个),然后是其余的。我没有丢失数据,但我需要它完整才能使用它。我试过了mmInStream.available();(见代码片段),但这太慢了。我也用 a 试过,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;
            }
        }


    }
4

1 回答 1

1

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

于 2013-01-24T17:48:35.707 回答