2017-05-04 18 views
0

我正在將Arduino BLE的gps位置數據作爲小塊(小於20字節)發送到我的android應用程序。我得到我的android應用程序中的數據,但我怎麼能將小塊組合到一個字符串。 這是我的arduino程序中的位置數據發送到Android應用程序的代碼。從Arduino BLE發送數據到Android,如何在Android應用程序中接收到的小數據塊UART數據

  String msg = "lat:"; 
      msg += GPS.latitude; 
      msg += ","; 
      msg.toCharArray(sendBuffer, 20); 
      ble.print("AT+BLEUARTTX="); 
      ble.println(sendBuffer); 

      String msg1 = "lon:"; 
      msg1 += GPS.longitude; 
      msg1 += ","; 
      msg1.toCharArray(sendBuffer, 20); 
      ble.print("AT+BLEUARTTX="); 
      ble.println(sendBuffer); 

      String msg2 = "speed:"; 
      msg2 += GPS.speed; 
      msg2.toCharArray(sendBuffer, 20); 
      ble.print("AT+BLEUARTTX="); 
      ble.println(sendBuffer); 

而在我的Android應用程序,這是代碼來獲取UART數據

if (action.equals(UartService.ACTION_DATA_AVAILABLE)) { 
      final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA); 
      try { 
       String receivedData = new String(txValue, "UTF-8"); 
       Log.i(TAG, "receivedData:" + receivedData); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
     } 

請參閱我的日誌,我如何獲取數據。

I/ContentValues: receivedData:lat:28.907892,lon:45 
I/ContentValues: receivedData:.789005,speed:0.02 

請問,我怎樣才能得到緯度,經度,速度作爲一個字符串從接收到的數據。感謝您的任何幫助!

回答

2

這個想法是將接收到的數據累加到一個字段變量中。累積數據按分隔符分割的子字符串。 下面是一個示例代碼:

//Field variable 
String mReceivedData = "";  

if (action.equals(UartService.ACTION_DATA_AVAILABLE)) { 
    final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA); 
    try { 
      mReceivedData += new String(txValue, "UTF-8"); 
      int delim; 
      while((delim = mReceivedData.indexOf('\n')) > -1) { 
       String dataToProcess = mReceivedData.subString(0, delim); 

       // Process the data 
       Log.i(TAG, "dataToProcess:" + dataToProcess); 

       mReceivedData = mReceivedData.subString(delim + 1); 
      } 
    } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
    } 
} 

也有可能正確格式化UartService接收到的數據,然後將它發送給你的活動。

+0

@謝仁,感謝您的幫助。 – proCoder

相關問題