如何通过蓝牙一起读取所有字节? [英] How to read all bytes together via Bluetooth?

查看:21
本文介绍了如何通过蓝牙一起读取所有字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如果您无法控制消息的发送方式,您可以一次读取一个字节,然后在遇到预定义的终止符时向您发送处理程序消息.例如: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;
}

这篇关于如何通过蓝牙一起读取所有字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆