2016-01-24 50 views
1

我正在通過藍牙創建一個通過arduino發送和接收數據的應用程序。發送工作正常,但是當收到數據時,我沒有收到發送字符串的前幾個字符。我總是沒有得到第一個字符,第二個我有時得到它,第三個我幾乎總是得到它,等等。Android無法通過藍牙接收所有字符

因此,例如,如果arduino發送「OK 1」,我收到「K 1」或「 1「或」1「,但絕不是完整的字符串。一個簡單的解決方法是添加幾個虛擬角色,但這是一個蠢事。

這裏的監聽傳入連接的處理方法,直接複製/ Android sample bluetooth code to send a simple string via bluetooth粘貼(儘管有一些修正):

void beginListenForData() 
{ 
    final Handler handler = new Handler(); 
    final byte delimiter = 10; //This is the ASCII code for a newline character 

    final boolean stopWorker = false; 
    final int readBufferPosition = 0; 
    final byte[]readBuffer = new byte[1024]; 
    Thread workerThread = new Thread(new Runnable() 
    { 
     public void run() 
     { 
      while(!Thread.currentThread().isInterrupted() && !stopWorker) 
      { 

       try 
       { 
        int bytesAvailable = inStream.available(); 
        int readBufferPosition2 = readBufferPosition; 
        if(bytesAvailable > 0) 

        { 
         byte[] packetBytes = new byte[bytesAvailable]; 
         inStream.read(packetBytes); 
         for(int i=0;i<bytesAvailable;i++) 
         { 
          byte b = packetBytes[i]; 
          if(b == delimiter) 
          { 
           byte[] encodedBytes = new byte[readBufferPosition2]; 
           System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); 
           final String data = new String(encodedBytes); 
           readBufferPosition2 = 0; 

           handler.post(new Runnable() 
           { 
            public void run() 
            { 
             result.setText(data); 
            } 
           }); 
          } 
          else 
          { 
           readBuffer[readBufferPosition2++] = b; 
          } 
         } 
        } 
       } 
       catch (IOException ex) 
       { 
       } 
      } 
     } 
    }); 

    workerThread.start(); 
} 

這裏是我的情況下,所有的代碼要測試它(警告:很多虛擬的和過時的代碼):

MainActivity.java http://pastebin.com/cdjW4Y1V XML佈局文件http://pastebin.com/Ruf5euPP

點擊第一個按鈕連接到Arduino並點擊第二按鈕發送一個字符串並開始接收數據。

所以,我完全不知道爲什麼它不起作用。它與TerminalBT工作正常,所以它不是與Arduino的問題,這是我的應用程序的問題,但爲什麼我隨機接收字符?

回答

0

我注意到的一件事是,你不應該使用10作爲分隔符。

我也遇到了這個錯誤之前,如果你使用10則有些時候它沒有得到正確識別。

您應該使用標準的Java函數來解析分隔符。

System.getProperty("line.separator"); 

//OR 

System.lineSeparator(); 
+0

我該如何使用此功能?我在哪裏把它放在我的代碼中? – Zezombye

+0

你這樣做.byte b = packetBytes [i] ;.只需比較一個.equals(System.lineSeparator())函數即可。如果您需要將字節轉換爲我無法檢查自己的字符串 – Neo