2011-11-10 10 views
3

Bluetooth入力ストリームの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); 

接続はうまくいきますが、別のデバイスにリンクされたBluetoothシリアルコンバータがあります。 2番目のものがオフになっている場合、私は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. 
} 

3秒以内に応答がない場合は、私の場合はresponderThreadは、ソケットを閉じ、実行は私がresponderThreadを作成し、クラスのcatchブロックに入ります。その後、例外が処理されます。