我正在开发一个应用程序,它通过蓝牙(从 Arduino 和安卓手机)接收 xml 作为字符串。
我从蓝牙获得无效/不完整的字符串。 蓝牙被定义为 Android 服务。 每次我收到一个字符串时,它都不是原来的形式,无论我是从 arduino 还是其他安卓手机发送的。 xml 解析功能正在运行我已经检查过了。
这是我接收字符串的代码
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
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
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sendXML(sbprint); // this method is for sending the xml string
sb.delete(0, sb.length()); // and clear
}
Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
Log.d("IncString", strIncom);
break;
}
};
};
这是我正在使用的示例 xml 字符串
<head><hbt v='100'/><hrg v='75'/></head>
我总是得到字符串但不是像这样完整的**v='100'/><hrg v='75'**
或 **</head>**
如果问题不清楚,请告诉我我会更新的任何内容
提前致谢
最佳答案
我用下面的代码成功地做到了这一点......
byte[] buffer = new byte[128]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
bytes = mmInStream.read(buffer);
byte[] readBuf = (byte[]) buffer;
String strIncom = new String(readBuf, 0, bytes); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) {
// add the current string to eol to a local string
String sbprint = sb.substring(0, endOfLineIndex);
// get the start and end indexes of the heading
int startHeading = sb.indexOf("HE");
int endHeading = sb.indexOf("/HE");
// set the heading
blahblah.setCurrentHeading(sb.substring((startHeading + 2), endHeading));
....
然后,在我从 arduino 发送的文本中检索到我想要的所有信息后,我调用了:
sb.delete(0, sb.length());
来 self 的 adruino 的字符串如下所示:::
void taskTransmitData(void)
{
// start the xml
Serial.print("HE");
Serial.print(pMyMemory->currentHeading);
Serial.print("/HE");
.....
Serial.println();
}
希望这有助于...
关于android - 在 Android 中通过蓝牙接收 xml 字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053358/