Android蓝牙配对,连接但从未接收到TextView的数据

时间:2014-07-04 07:07:06

标签: java android bluetooth arduino

我正在尝试从非Android蓝牙设备(带有HC-06的arduino)接收数据(字符串)。 arduino中的代码看起来很好,它在连续循环中发送一个字符串,我能够使用串行监视器看到它。 但是当我尝试将它与我的Android手机一起使用时,它会被配对,连接并显示" Connect"在敬酒,但我从来没有能够收到它的字符串并在文本视图上显示它。如果我做错了,请告诉我。

我的活动类里面的代码,在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);

Inside 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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我可以通过调用

来解决这个问题
connectedThread.start();

之后,

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

在SUCCESS_CONNECT案例中排队。