2013-02-24 49 views
1

我正在开发一个应用程序,它通过蓝牙接收xml作为字符串(来自Arduino和Android手机)。在Android中通过蓝牙接收xml字符串的错误

我从蓝牙无效/不完整的字符串。 蓝牙被定义为一项Android服务。 每当我收到一个字符串,它不是原来的形式,我从Arduino或其他Android手机发送它。 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>**

如果问题不清楚告诉我任何我会更新的东西

thanx提前

回答

1

我用下面的代码这样做成功...

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)); 

    .... 

sb.delete(0, sb.length()); 

的STRI:

然后我检索到的所有信息后,我从我所谓的Arduino的发送文本通缉吴从我adruino未来看起来如下:::

void taskTransmitData(void) 
{ 
    // start the xml 
    Serial.print("HE"); 
    Serial.print(pMyMemory->currentHeading); 
    Serial.print("/HE"); 

    ..... 

    Serial.println(); 

} 

希望这有助于...

+0

感谢您的帮助 – Neo 2013-02-27 18:03:23

相关问题