Reputation: 4958
I got this rare situation in which I am trying to connect a BluetoothSocket to a server and the connect method just wouldn't return. Here is my code:
device = _adapter.getRemoteDevice(_address);
socket = device.createInsecureRfcommSocketToServiceRecord(_uuid);
_adapter.cancelDiscovery();
socket.connect();
This is running in an AsyncTask and the task never finishes as connect is blocked forever... this also prevents reconnecting to the server (I haven't figured out yet whether I can't use BT completely or just can't reconnect using the same target address and UUID). Is there a way to do connect with a timeout?
Upvotes: 3
Views: 2714
Reputation: 1610
One way to solve your issue is to have another Thread interrupt the AsyncTask by calling cancel(true) (which will interrupt the AsyncTask Thread) or by calling close() on the Socket. It could for example be done by the main thread, by posting a delayed callback to its handler just before socket.connect() and which will be removed directly after.
So in your case
post timeout callback to handler, with reference to socket or to this (AsyncTask)
try {
socket.connect();
} catch (IOException e) { // and/or InterruptedException
couldn't connect
} finally {
remove callback (this must be done here as the IO exception might be caused by something other than the timeout callback)
}
Upvotes: 2