繁体   English   中英

无法从Android蓝牙连接接收数据

[英]Trouble receiving data from Android Bluetooth connection

我有一个连接到蓝牙伴侣银芯片的android应用程序。 我正在测试它的发送/接收功能。 通常,我一直在android dev网站上关注蓝牙示例。

我可以说发送数据是可行的,因为当我向芯片写入(“ $$$”)时,它将进入命令模式并非常快速地闪烁其状态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””,使我相信它是一个内存地址。 不过,我仍然不知道该怎么办。

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

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

指定UTF-8是什么与众不同。

暂无
暂无

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

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