java - Android 蓝牙已配对、连接但从未将数据接收到 TextView

标签 java android bluetooth arduino

我正在尝试从非 Android 蓝牙设备(带有 HC-06 的 arduino)接收数据(字符串)。 arduino 内部的代码看起来相当不错,它在连续循环中发送一个字符串,我能够使用串行监视器看到它。 但是当我尝试将它与我的 Android 手机一起使用时,它会配对、连接并在 toast 中显示“连接”,但我始终无法接收其字符串并将其显示在 TextView 上。请告诉我我是否做错了什么。

我的 Activity 类中 onCreate 方法中的代码:

public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what)
            {
            case SUCCESS_CONNECT:
                ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                Toast.makeText(getApplicationContext(), "Connect", 0).show()

                break;

            case MESSAGE_READ:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, 0).show();              
                tvTest.setText(string);

ConnectedThread 类内部:

public void run() {
        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                buffer = new byte[1024];
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

最佳答案

我可以通过调用来解决这个问题

connectedThread.start();

之后,

ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);

SUCCESS_CONNECT 情况下的行。

关于java - Android 蓝牙已配对、连接但从未将数据接收到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568499/

相关文章:

android - 输入第一个字符时,软键盘将布局向上推

不幸的是,android 应用程序在从真实设备运行时停止了

linux - 在 Linux 命令行上以编程方式删除所有蓝牙设备

linux - Qt 蓝牙与 Linux

java - 我可以在使用 Java Socket 实现的网络服务器上使用任何身份验证机制吗?

java - 停止正在进行的可运行 Android

java - 使用 Spring Boot 配置 Logback

安卓截击 : how to handle the error response

android - BluetoothServerSocket.accept() 返回未连接的 BluetoothSocket 的问题

java - Cassandra 的节俭运输异常(exception)