繁体   English   中英

通过蓝牙android接收字符串(无换行或回车)

[英]Receive string via Bluetooth android (without line feed or Carriage Return)

关于如何从蓝牙设备接收数据(字符串)的堆栈溢出问题很多,但我从未见过关于如何在不检查LF或CR的情况下如何接收数据(字符串)的问题。

当设备在字符串的末尾发送LF时,此代码可以完美工作:

final Handler handler = new Handler();
    final byte delimiter = 10; //ASCII code for Line Feed

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];

    try {
        inStream = btSocket.getInputStream();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }



    Thread workerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted() && !stopWorker) {
                try {
                    int bytesAvailable = inStream.available();
                    if (bytesAvailable > 0) {
                        byte[] packetBytes = new byte[bytesAvailable];
                        inStream.read(packetBytes);
                        for (int i = 0; i < bytesAvailable; i++) {
                            byte b = packetBytes[i];
                            if (b == delimiter) {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                readBufferPosition = 0;
                                handler.post(new Runnable() {
                                    public void run() {
                                        //test
                                        textview1.setText(data);
                                    }
                                });
                            } else {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                } catch (IOException ex) {
                    stopWorker = true;
                }
            }
        }
    });
    workerThread.start();

但是发送字符串的设备不会发送换行符,也不会发送CR。 我尝试了很多事情(还有Google的蓝牙指南( http://developer.android.com/guide/topics/connectivity/bluetooth.html ))。 我想接收所有发送到应用程序的数据(并进行测试以在textview中显示接收到的String)。

在此先感谢,Michielvk

假设所有字符串都以“ 1”字符开头,那么应该可以通过替换final byte delimiter = 10;来读取倒数第二个字符串final byte delimiter = 10; final byte delimiter = 49; (因为49是ASCII表中的“ 1”的十进制表示)。

如果没有后缀定界符,则无法读取最后一个字符串(并且断言您正在读取完整的字符串,而不仅仅是一部分)。

编辑:

您在此注释提要中提供了协议的文档。 doc说: 结果字符串由38个ASCII字符组成。

根据每个响应均由38个ASCII字符组成的事实,您应该能够通过将: if (b == delimiter) {替换为: if (readBufferPosition >= 37) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM