I had a problem where bluetooth would connect and then disconnect immediately, I looked at a lot of solutions but in the end this simple one solved my issue.
However I'm keen to get feedback as I'm sure there will be some inherent danger I have missed.
Solution: I put the socket.connect() in a loop (as below). Note: this worked for me, where other solutions on stack overflow did not
- Most obviously I've not set a timeout for the while loop (I'll deal with that later)
- I'm also aware that there can be multiple uuids per device, but that's not the problem I was trying to solve.
fun connect(device: BluetoothDevice) {
bluetoothAdapter?.cancelDiscovery()
val socket = device.createRfcommSocketToServiceRecord(device.uuids[0].uuid)
Thread().run {
while (!socket.isConnected) {
try {
socket.connect()
} catch (e: Exception) {
Log.d("DEVICE_CONNECT_FAIL", e.toString())
}
}
if (socket.isConnected) {
interrupt()
}
}
}