如何阅读通过蓝牙所有字节在一起吗?蓝牙、字节

2023-09-05 07:09:51 作者:趁年轻づ

我有一个使用蓝牙接收来自其他设备的一些数据(字节)的应用程序。一切都很顺利,但我在收到字节一起有一个小问题。接收的字节数后,我告诉他们在吐司只是为了测试他们。当其它设备发送10字节一起(例如:ABCDEFGHIJ),该计划将采取的第一个字节A仅显示其放在烤面包,然后去第二次迭代和读取其他9个字节,并显示 BCDEFGHIJ上祝酒。这是我的code:

I have an application that uses the bluetooth to receive some data (bytes) from other device. everything is going well, but I have a small issue on receiving the bytes all together. After receiving the bytes I show them on a Toast just to test them. When the other device sends 10 bytes together (for example: "ABCDEFGHIJ"), the program will take the first byte "A" only and show it on a Toast, then go to the second iteration and read the other 9 bytes and show "BCDEFGHIJ" on the Toast. Here is my code:

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,我有:

In the MainActivity, I have:

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

            // ...
        }
    }
};

如何才能收到的所有字节在一起?!

How can I receive all the bytes together?!

推荐答案

嗯最有可能的罪魁祸首是在你发送的邮件的方式。您收到没有问题,它会因为它被写入接收的字节数(到你的1024)。

Mmm most likely the culprit is in the way you're sending the messages. Your receive has no problems, it will receive as many bytes (up to your 1024) as it is written to.

如果您通过邮件发送你也许可以读一个字节的时间,然后发送邮件处理程序,当你打了predefined终结的方式进行控制。例如:ABCDEFGHIJ#,其中#是终结者。

If you have no control over the way the messages are sent you can probably read one byte at a time and then send a handler message you when you hit a predefined terminator. Ex: "ABCDEFGHIJ#" where # is the terminator.

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