I'm writing a peer Bluetooth app that connects to itself in another phone. It has to deal with the situation that the other instance may not yet be active, so it catches the IOException from the failed connect and retries after a short while (on its own thread).
BluetoothSocket clientSocket = getBluetoothDevice().createRfcommSocketToServiceRecord(MY_UUID);
while(!connected) {
try {
Log.d(APP_NAME, "About to connect");
// Connect to the remote server. If the server is not available
// an exception is thrown
clientSocket.connect();
connected = true;
Log.d(APP_NAME, "Connected");
} catch (IOException connectException) {
Log.d(APP_NAME, "Failed to connect: " + connectException.getMessage()); // this is the error message
try {
Thread.sleep(sleepTime);
} catch (InterruptedException ignored) {}
}
}
if (connected) {
...
The error message is infamous for bad grammar (a Google issue was raised in 2015 and is still not fixed) but more importantly it's completely unclear what the error really is and how to respond. The issue I have is that when running the app in Android Studio I see messages in Logcat:
W A resource failed to call close.
which I'm assuming are related to this. The docs don't say if the socket is still usable after this error. I've assumed it is and it does appear to be - the code works in that when the remote app becomes active, it connects OK. But perhaps I need to close it, and if so I guess I'd need to create a new socket.
Although there are no other error messages, the UI eventually freezes and an ANR crash follows. Again I'm guessing this is all related. Advice is appreciated.