【问题标题】:Trouble receiving data from Android Bluetooth connection无法从 Android 蓝牙连接接收数据
【发布时间】:2014-05-06 08:19:46
【问题描述】:

我有一个连接到蓝牙伴侣银芯片的安卓应用程序。我正在测试它的发送/接收功能。大多数情况下,我一直在关注 android 开发网站上的蓝牙示例。

我可以说发送数据有效,因为当我向芯片写入("$$$") 时,它会进入命令模式并快速闪烁其状态 LED。当芯片进入命令模式时,它会发送一个回复:“CMD”。我无法收到此回复。

当我按下一个按钮时,会执行以下代码。 mct 是我用来读写的全局 ConnectedThread。尽管形式很糟糕,但所有函数都在 MainActivity.java 中

if(connected){
    if (cmdMode == false){
        mct.write("$$$".getBytes());  //enter command mode
            mct.listen();
        TextView lbl_history = (TextView) findViewById(R.id.lbl_history);
        lbl_history.setText(message);
        cmdMode = true;
    }
    else{
        mct.write("k,\n".getBytes());  //kill the connection
        cmdMode = false;
    }

}

我的交流线程:

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
    }

    public void listen() {
        handled = false;
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()
        reply=null;
        while (reply==null) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                reply = buffer.toString(); 
                    //message is a global String to store the latest message received
                    message = reply;                             
            } catch (IOException e) {
                break;
            }
        }
        reply = null;
    }
//write and cancel functions removed for simplicity
}

当我运行这段代码时,结果是一个文本视图,上面写着“[B@415f8910”,我认为它是垃圾。多次运行相同的代码会产生相似的结果,只是最后几位不同。预期的结果将是“CMD”。关于这里的问题有什么想法吗?我是 android 开发新手,感谢您的帮助。

进一步检查显示,多次运行严格增加“[B@415f8910”,使我相信它是一个内存地址。不过,我不知道该怎么处理它。

【问题讨论】:

    标签: java android bluetooth


    【解决方案1】:

    我发现了问题。我需要调用 String 构造函数来正确转换数据,而不是直接在字节数组上调用“toString()”:

    String message = new String(buffer, "UTF-8");
    

    指定 UTF-8 是造成差异的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2012-12-12
      • 2018-07-07
      • 2013-07-14
      • 2012-02-28
      相关资源
      最近更新 更多