2011-11-10 32 views
3

我應該在readLine上爲藍牙輸入流插入一個超時。Android:BluetoothSocket readLine timeout

BluetoothDevice device = BluetoothAdapter.getDefaultAdapter() 
      .getRemoteDevice("00:00:00:00:00:00"); 

    sock = device.createInsecureRfcommSocketToServiceRecord(UUID 
      .fromString(insecureUUID)); 
    sock.connect(); 

    in = new BufferedReader(new InputStreamReader(sock.getInputStream())); 
    String line = in.readLine(); //if no answer from device..i'll wait here forever 

    do { [...] 

    } while ((line = in.readLine()) != null); 

連接工作正常,但我有一個藍牙串行轉換器鏈接到另一個設備。如果第二個關閉,我會永遠等待readLine。任何機會,我可以拋出異常或超時? 謝謝!

回答

1

我有同樣的問題,我通過創建一個擴展線程的ResponderThread來解決它。這個線程等待一段時間,然後檢查輸入流變量是否已經改變。

try { 
    bufferedReader = new BufferedReader(new InputStreamReader(
      bluetoothSocket.getInputStream())); 

    responderThread = new ResponderThread(bluetoothSocket, ACCESS_RESPONSE); 
    responderThread.start(); 
    response= bufferedReader.read(); 

} catch (IOException ioe) { 
    // Handle the exception. 
} 

在我的情況下responderThread關閉套接字是否有3秒內沒有響應,並執行進入其中i創建responderThread類的catch塊。然後處理異常。