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

Eng*_*uad 11 java android bytearray bluetooth stream

我有一个应用程序,使用蓝牙从其他设备接收一些数据(字节).一切进展顺利,但我在接收所有字节时遇到了一个小问题.收到字节后,我在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

            // ...
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我怎样才能一起收到所有字节?!

bro*_*ody 7

嗯,最有可能的罪魁祸首就在于你发送邮件的方式.您的接收没有问题,它将收到与写入的字节数(最多1024个).

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

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


TJD*_*TJD 5

蓝牙连接是基于流的,而不是基于数据包的.无法保证或尝试保留打包.因此,任何数量的写入都可以导致任意数量的读取,只保证字节流是正确的.如果需要检测数据包,则需要提供自己的数据包结构来包装数据.例如,在每个数据包之前添加一个长度字段,以便您可以在接收方重建.


tru*_*lue 5

@broody 接受的答案是正确的。但如果数据本身包含“#”,则可能难以获取数据。因此,根据我的说法,最好的方法是在将数据发送到您的 Android 应用程序的设备中附加 '\n' 后跟 '\r'(或任何其他不太可能作为数据参考 ASCII 表的字符)。它只是作为换行符并标记数据的结尾。

例如:ABCDEFGH\n\r

那么你的代码可以是这样的:

byte[] buffer = new byte[1024];
 while (true) {

         // Read from the InputStream
          buffer[bytes] = (byte) mmInStream.read();                 
         // Send the obtained bytes to the UI Activity
 if ((buffer[bytes] == '\n')||(buffer[bytes]=='\r'))
 {
   mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
   bytes=0;
 }
 else
 bytes++;
}
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助