I’m working on an app that works alternatively as a client or as a server for GATT connections and the related data exchange.
The app has a status bar with the bluetooth connection status.
The app works fine except when the server is closed
override fun onDestroy() {
super.onDestroy()
if (preference_BluetoothMode == "Server")
{
bluetoothService!!.stopServer()
}
else
{
bluetoothService!!.disconnect()
}
// other
}
fun stopServer() {
if (mGattServer != null) {
mGattServer!!.close()
}
}
In this case the client is not informed about the new server status and consequently the status bar cannot be updated.
In particular, BluetoothGattCallback does not receive notifications.
Note that I tried, without success, to disconnect all devices from the server (before closing it), using the following function:
fun disconnectFromGattServer() {
devicesArrayList.forEach { device ->
mGattServer!!.cancelConnection(device)
}
I need to update the client’s status bar with the new server status when it is closed.
It may not be an elegant solution, but it seems to work:
I inserted a disconnection message in the on Destroy function and moved the closing of the Gatt Server to the onUnbind function of the service
override fun onDestroy() {
super.onDestroy()
if (preference_BluetoothMode == "Server")
{
bluetoothService!!.sendMessageFromServer("I'M DISCONNECTING")
// bluetoothService!!.stopServer()
}
else
{
bluetoothService!!.disconnect()
}
// other
}
service
override fun onUnbind(intent: Intent?): Boolean {
close()
return super.onUnbind(intent)
}
@SuppressLint("MissingPermission")
private fun close() {
bluetoothGatt?.let { gatt ->
gatt.close()
bluetoothGatt = null
}
if (mGattServer != null) {
mGattServer!!.close()
}
// other
}