2010-06-17 32 views
2

你好,我想在Android設備之間進行對話。我使用藍牙來做到這一點,但它不起作用,我無法正確讀取其他設備的數據。BluetoothChat無效

交談是:

我:女貞

設備:P 設備:鉚釘

你能幫助我嗎?

私有類ConnectedThread擴展Thread {

private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket) { 
     Log.d(TAG, "create ConnectedThread"); 
     mmSocket = socket; 
     //InputStream tmpIn = null; 
     OutputStream tmpOut = null; 
     BufferedInputStream tmpIn=null; 

     int INPUT_BUFFER_SIZE=32; 
     // Get the BluetoothSocket input and output streams 
     try { 
      //tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
      tmpIn = new BufferedInputStream(socket.getInputStream(),INPUT_BUFFER_SIZE); 

     } catch (IOException e) { 
      Log.e(TAG, "temp sockets not created", e); 
     } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     Log.i(TAG, "BEGIN mConnectedThread"); 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (true) { 
      try { 
       // Read from the InputStream 

       bytes = mmInStream.read(buffer); 
       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 
       Log.e(TAG, "disconnected", e); 
       connectionLost(); 
       break; 
      } 
     } 
    } 
+0

這兩個設備?某些設備的藍牙實際上並不工作,即使它們使用的是Android 2.0。例如HTC Droid。 – 2010-06-19 19:35:05

+0

這是相同的問題,因爲http://stackoverflow.com/questions/9270965/bluetooth-spp-receive-some-the-package-frame-can-lost-or/32887129#32887129 – jgrocha 2015-10-18 22:52:53

回答

1

用於溶液的修復是在所連接的線程創建字符串,調用read()上的InputStream後直接,和然後使字符串回顯示主線程。無論出於何種原因,在線程之間傳遞字節數組導致重大重複和數據丟失。

修改的run()代碼:

public void run() { 
    byte[] buffer = new byte[256]; // buffer store for the stream 
    int bytes; // bytes returned from read() 

    // Keep listening to the InputStream until an exception occurs 
    while (true) { 
     try { 
      // Read from the InputStream 
      bytes = mmInStream.read(buffer); 
      String readMessage = new String(buffer, 0, bytes); 
      // Send the obtained bytes to the UI Activity 
      mHandler.obtainMessage(MESSAGE_READ, bytes, -1, readMessage) 
        .sendToTarget(); 
     } catch (IOException e) { 
      break; 
     } 
    } 
} 

而且處理器接待:

case MESSAGE_READ: 
     // Read in string from message, display to mainText for user 
     String readMessage = (String) msg.obj; 
     if (msg.arg1 > 0) { 
      mainText.append(readMessage); 
     }