I tried using BluetoothSocket.close() but it doesnt work. It only works when I disconnect to an Android device. When I try to disconnect to an iOS device, the Bluetooth Socket is closed, but the bluetooth connection still persists- still connected.
Here's how I establish the connection
fun connectDevice(device: BluetoothDevice) {
bluetoothAdapter?.cancelDiscovery()
if (device.bondState != BluetoothDeviceInfo.BondState.PAIRED.value) {
device.createBond()
} else {
val uuids = bluetoothAdapter?.getRemoteDevice(device.address)?.uuids
uuids?.let {
var socket: BluetoothSocket? = null
bluetoothJob = CoroutineScope(Dispatchers.IO).launch {
for (uuid in it) {
try {
val convertedUUID = uuid.uuid
socket = device.createRfcommSocketToServiceRecord(convertedUUID)
socket?.connect()
bluetoothSocket = socket
break
} catch (e: Exception) {
LogUtils.d(e.message.toString())
socket?.close()
}
}
}
}
}
}
Here's how I disconnect the connection
bluetoothAdapter?.cancelDiscovery()
CoroutineScope(Dispatchers.IO).launch {
try {
bluetoothJob?.cancel()
delay(1000L)
bluetoothSocket?.let {
it.outputStream.close()
it.inputStream.close()
}
delay(1000L)
bluetoothSocket?.close()
bluetoothSocket = null
} catch (e: Exception) {
LogUtils.d(e.message.toString())
}
}
I have tried these possible solution but still doesn't work.
- Wrap the bluetooth connection inside a coroutine Job and then cancel it before closing the bluetooth socket
- Closing the outputStream and inputStream before closing the bluetooth socket
- Adding delays between processing