我的应用程序中有一个与Arduino通信的Handler的奇怪行为。在尝试调试问题时,我有很多头痛。我有点解决了这个问题,但我想知道为什么会发生这种情况?
我正在从Arduino向Android发送简单的JSON {"name": "Afghanistan", "code": "AF"}
。
public void run() {
byte[] buffer = new byte[1024]; // 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
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
// <What i added>
String readMessage = new String(buffer, 0, bytes);
outputBefore += readMessage;
if (outputBefore.endsWith("\n")){
Log.d(TAG, "Before Handler: " + outputBefore);
outputBefore = "";
}
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
线h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
发送缓冲区,所有魔法开始......
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
outputAfter += strIncom;
if (outputAfter.endsWith("\n")){
Log.d(TAG, "After Handler: " + outputAfter);
outputAfter = "";
}
break;
}
};
};
正如您在LogCat的输出中看到的,有时消息是相同的。在Handler之前,消息是正常的,我测试了20k次并且没有出现错误,但是使用Handler出错了。即使BluetoohSample使用Handler也失败了!这到底是什么意思?
09-25 12:18:18.742: D/bluetooth2(15858): Before Handler: {"name": "Afghanistan", "code": "AF"}
09-25 12:18:18.742: D/bluetooth2(15858): After Handler: {"name": "Afghanistan: "AF"}
09-25 12:18:18.742: D/bluetooth2(15858): After Handler: : "AF"}
09-25 12:18:19.142: D/bluetooth2(15858): Before Handler: {"name": "Afghanistan", "code": "AF"}
09-25 12:18:19.152: D/bluetooth2(15858): After Handler: {"name": "Afghanistan", "code": "AF"}
09-25 12:18:19.522: D/bluetooth2(15858): Before Handler: {"name": "Afghanistan", "code": "AF"}
09-25 12:18:19.522: D/bluetooth2(15858): After Handler: AAfghanistn", "code"n", "code": "AF"}