2013-02-24 71 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

相關問題