2011-09-30 93 views
0

我有一個BluetoothSocket,我正在讀取數據,使用單獨的線程進程從GUI。我將InputStream包裝在DataInputStream中,這樣我就可以使用readFully(..)等待指定數量的數據。我可以運行這個代碼大約一個小時,然後程序鎖定,當我調試它在readFully()卡住。我包含在我的GUI線程BroadcastReceivers中,以在藍牙斷開連接時通知我。 BroadCastReceivers從未收到通知。不確定爲什麼設備停止發送數據,如果情況確實如此,或者不確定是否藍牙SPP被丟棄,但套接字仍然打開,所以藍牙斷開連接消息從未發生過。任何關於修復的想法,甚至爲什麼或如何調試爲什麼卡住將不勝感激。DataInputStream卡住readFully

這是我ReadBlueTooth類...

public class ReadBlueToothData extends Thread { 
    private BluetoothSocket btSocket; 
    private BluetoothAdapter bta; 
    private DataInputStream dinput; 

    public ReadBlueToothData(Activity a,String mac) { 
     ...init object... 
    } 

    public void run() { 
     // if socket connected otherwise stop 
     if (dinput==null) return; 

     byte[] byteArray = new byte[3]; 


     while (!Thread.interrupted()) { 

      dinput.readFully(byteArray, 0, 3); 

      // DO something .... 
     } 

     // close out InputStream nicely 
     if (dinput!=null) { 
      try { 
       dinput.close(); 

      } catch (IOException e) { } 
     } 

     if (btSocket != null) { 
      try { 
       btSocket.close(); 
      } catch (IOException e) {} 
     } 
    } 
} 
+0

有時候還是會碰到這個......希望有人會有答案。 – JPM

回答

1

我再也不會被優雅地做這個檢測藍牙斷開連接時出現此錯誤。

dinput.close(); 
readBlueToothData().interrupt(); 
btSocket.close(); 
//make sure to check for nulls for all these too 

然後通過查看進入的數據進行檢查,如果緩衝區的大小沒有增加,則也會調用斷開連接。