1

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()
                }
            }
        }
Gugu72
  • 2,052
  • 13
  • 35
rsmediapc
  • 21
  • 5

1 Answers1

0

Read this documentation https://developer.android.com/reference/android/bluetooth/BluetoothDevice#createRfcommSocketToServiceRecord(java.util.UUID) Look on how a secure connection can be established.

I suggest you to try with an insecure type of connection with a correct UUID

Also this question can help you.

Pico
  • 79
  • 11
  • Thanks, I have been using that documentation from the start. I think the problem goes deeper in that I'm trying to connect with an already paired 3rd party device. It's likely that the phones OS (Samsung) has some magic to retain device connections. The device may need to be paired by my app instead of by the phone. I also get different results depending on what I'm trying to connect to. – rsmediapc Apr 15 '21 at 21:35