我有一个android应用程序连接到一个蓝牙伴侣银芯片。我正在测试它的发送/接收功能。大多数情况下,我一直在效仿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",使我相信这是一个内存地址。不过,我还是不知道该怎么办。
发布于 2014-05-06 00:19:46
我发现了问题。我需要调用字符串构造函数来正确地转换数据,而不是直接调用字节数组上的"toString()“:
String message = new String(buffer, "UTF-8");指定UTF-8是造成差异的原因。
https://stackoverflow.com/questions/23450961
复制相似问题