Reputation: 1685
I should insert a timeout on a readLine for a bluetooth input stream.
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);
The connection works fine, but i've got a bluetooth serial converter linked to another device. If the second one is turned off i'll wait forever on the readLine. Any chance i can throw an exception or a timeout? Thanks!!
Upvotes: 3
Views: 1439
Reputation: 316
I had the same problem and i solved it by creating a ResponderThread that extends Thread. This thread waits a certain amount of time and after that it checks if the input stream variable have changed.
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.
}
In my case the responderThread closes the socket if there is no response within 3 seconds and the execution goes into the catch block of the class where i create the responderThread. Then the exception is handled.
Upvotes: 1