0

Right now I have a code that connects the phone to a bluetooth printer, the problem is that I want to close that connection while not needing it, in other words I just want the device to connect to the printer when it needs to send a file and I want it to then disconnect. To connect to the printer I'm using the following code:

fun connectBluetooth(address: String): Boolean {
        var connectSuccess = true

        try {
            if (bluetoothSocket == null) {
                val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
                val device: BluetoothDevice = bluetoothAdapter!!.getRemoteDevice(address)
                bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID)

                bluetoothSocket!!.connect()
            }
        } catch (e: IOException) {
            connectSuccess = false
            e.printStackTrace()
        }
        return connectSuccess
    }

I'm wondering how I can then close the connection, right now I have been simply doing

bluetoothSocket = null

but I highly doubt that is the right way to do it

ExCr4Per
  • 97
  • 1
  • 1
  • 6

1 Answers1

0

Ok it wasn't as hard as I thought it would be, all that had to be done was to close the output stream that I was using in order to send the file to the printer.

I found out about this thanks to the link that was refered to me in the comments by vyas dipak: Disconnect a bluetooth socket in Android

All I did was create this small function and it all worked out well

fun disconnectBluetooth(){
    val outputStream : OutputStream? = null

    try {
        outputStream?.close()
    } catch (e: IOException ){}

    try {
        bluetoothSocket?.close()
    } catch (e: IOException){}

    bluetoothSocket = null
}
ExCr4Per
  • 97
  • 1
  • 1
  • 6