2013-08-24 49 views
0

我已經設置了一個套接字接收來自藍牙設備的數據。接收緩衝區被設置爲在退出線程之前收集8個字節的數據,但緩衝區不會前進以存儲下一個字節的數據。我將緩衝區設置爲8並循環,直到緩衝區滿。藍牙接收數據

 private class ConnectedThread extends Thread { 

    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket) { 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = btSocket.getInputStream(); 
      tmpOut = btSocket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
     } 

    public void run() { 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 

       InputStream mmInStream = btSocket.getInputStream(); 

       byte[] readBuffer = new byte[8]; 
       int read = mmInStream.read(readBuffer); 
       while(read != -1){ 

        Log.d(TAG, " SizeRR " + read); 
        read = mmInStream.read(readBuffer); 
       } 


      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

Log.d(SizeRR 1)讀出的8倍

+0

你期待什麼輸出? – frogmanx

+0

我試圖通過readBuffer [7]將數據讀入數組readBuffer [0]。 –

回答

0

InputStream.read()被設計爲返回一個抽象INT,所以它將總是從0-255打印數。

嘗試代替所讀取的(字節[]緩衝液)的方法,將其寫入數據的buffer.length量從流,並將數據複製直到陣列:

public void run() { 

    // Keep listening to the InputStream until an exception occurs 
    while (true) { 
     try { 

      InputStream mmInStream = btSocket.getInputStream(); 
      byte[] readBuffer = new byte[8]; 
      mmInStream.read(readBuffer); 

     } catch (IOException e) { 
      break; 
     } 
    } 
} 
+0

接收函數正常,但它只返回1個字節。接收緩衝區應該有8個字節可用。 –

+0

但是你的原始函數中有8個字節。如果Log.d(SizeRR 1)返回8次,那麼8個整數等於8個字節。 – frogmanx

+0

你是對的我得到8個字節。我認爲mmInStream.read(readBuffer)會一次將全部8個讀入readbuffer,然後退出。我想我會嘗試一個循環來分別讀取每個8字節。 –