Disconnect a Bluetooth Socket in Android

Disconnect a bluetooth socket in Android

Please remember to close your Input/output streams first, then close the socket.

By closing the streams, you kick off the disconnect process. After you close the socket, the connection should be fully broken down.

If you close the socket before the streams, you may be bypassing certain shutdown steps, such as the (proper) closing of the physical layer connection.

Here's the method I use when its time to breakdown the connection.

/**
* Reset input and output streams and make sure socket is closed.
* This method will be used during shutdown() to ensure that the connection is properly closed during a shutdown.
* @return
*/
private void resetConnection() {
if (mBTInputStream != null) {
try {mBTInputStream.close();} catch (Exception e) {}
mBTInputStream = null;
}

if (mBTOutputStream != null) {
try {mBTOutputStream.close();} catch (Exception e) {}
mBTOutputStream = null;
}

if (mBTSocket != null) {
try {mBTSocket.close();} catch (Exception e) {}
mBTSocket = null;
}

}

EDIT: Adding code for connect():

// bluetooth adapter which provides access to bluetooth functionality. 
BluetoothAdapter mBTAdapter = null;
// socket represents the open connection.
BluetoothSocket mBTSocket = null;
// device represents the peer
BluetoothDevice mBTDevice = null;

// streams
InputStream mBTInputStream = null;
OutputStream mBTOutputStream = null;

static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

/**
* Try to establish a connection with the peer.
* This method runs synchronously and blocks for one or more seconds while it does its thing
* SO CALL IT FROM A NON-UI THREAD!
* @return - returns true if the connection has been established and is ready for use. False otherwise.
*/
private boolean connect() {

// Reset all streams and socket.
resetConnection();

// make sure peer is defined as a valid device based on their MAC. If not then do it.
if (mBTDevice == null)
mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC);

// Make an RFCOMM binding.
try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
} catch (Exception e1) {
msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage());
return false;
}

msg ("connect(): Trying to connect.");

try {
mBTSocket.connect();
} catch (Exception e) {
msg ("connect(): Exception thrown during connect: " + e.getMessage());
return false;
}

msg ("connect(): CONNECTED!");

try {
mBTOutputStream = mBTSocket.getOutputStream();
mBTInputStream = mBTSocket.getInputStream();
} catch (Exception e) {
msg ("connect(): Error attaching i/o streams to socket. msg=" + e.getMessage());
return false;
}

return true;
}

Android : How to disconnect already connected bluetooth device?

Kotlin

private fun disconnect(device: BluetoothDevice) {
val serviceListener: BluetoothProfile.ServiceListener = object :
BluetoothProfile.ServiceListener {
override fun onServiceDisconnected(profile: Int) {}

@SuppressLint("DiscouragedPrivateApi")
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
val disconnect = BluetoothA2dp::class.java.getDeclaredMethod(
"disconnect",
BluetoothDevice::class.java
)
disconnect.isAccessible = true
disconnect.invoke(proxy, device)
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
}
}
BluetoothAdapter.getDefaultAdapter()
.getProfileProxy(this, serviceListener, BluetoothProfile.A2DP)
}

Android Kotlin - How can I programmatically disconnect a bluetooth device?

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
}


Related Topics



Leave a reply



Submit