如何通过蓝牙一起读取所有字节?


问题内容

我有一个使用蓝牙从其他设备接收一些数据(字节)的应用程序。一切进展顺利,但是我在接收所有字节时遇到了一个小问题。收到字节后,我将它们显示在Toast上只是为了对其进行测试。当另一台设备一起发送10个字节(例如:“
ABCDEFGHIJ”)时,程序将仅获取第一个字节“ A”并将其显示在Toast上,然后转到第二个迭代并读取其他9个字节并显示“
BCDEFGHIJ”在吐司上。这是我的代码:

byte[] buffer = new byte[1024]; // Read 1K character at a time.
int bytes = 0; // Number of bytes.

while(true)
{
    try
    {
        // Read from the InputStream.
        bytes = bInStream.read(buffer);

        // Send the obtained bytes to the MainActivity.
        mainActivityHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
    }
    catch(IOException e)
    {
        connectionLost();
        break;
    }
}

在MainActivity中,我有:

// The Handler that gets information back from the BluetoothManager.
private final Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        switch(msg.what)
        {
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;

                // construct a string from the valid bytes in the buffer.
                String readMessage = new String(readBuf, 0, msg.arg1);
                Toast.makeText(MainActivity.this, readMessage, Toast.LENGTH_SHORT).show();
                break;

            // ...
        }
    }
};

如何一起接收所有字节?


问题答案:

嗯,最可能的罪魁祸首是您发送邮件的方式。您的接收没有问题,它将接收与写入一样多的字节(最多1024个字节)。

如果您无法控制消息的发送方式,则可能一次可以读取一个字节,然后在遇到预定义的终止符时向您发送处理程序消息。例如:“
ABCDEFGHIJ#”,其中#是终止符。

String msg = "";
byte ch;
while((ch=mInStream.read())!='#') {
    bytes++;
    msg+=ch;
}