I am trying to disconnect characteristic notifications as I am exiting my app. Here is how I am doing it in my exitCleanup() function:
if (btGatt != null && mWriteChar != null) {
boolean b=btGatt.setCharacteristicNotification(mWriteChar, false);
Log.w("AppInfo", "Exiting and Unsubscribing: " + b);
}
The log shows: Exiting and Unsubscribing: true
. So far so good.
I then attempt to disconnect the GATT object altogether using the following:
if (btGatt != null && btManager!=null && btManager.getConnectionState(btDevice, BluetoothProfile.GATT) != BluetoothProfile.STATE_DISCONNECTED ) {
//Making sure that gatt and bt manager are still with us
//Also making sure that the connection state is NOT disconnected
btGatt.disconnect();
btGatt.close();
Log.w( "AppInfo", "FINISHING. Connection state=" + btManager.getConnectionState(btDevice, BluetoothProfile.GATT) );
}
This is where things get weird. The log now displays the following: FINISHING. Connection state=2
, indicating that the BluetoothDevice is still connected.
This is a problem, because when the app finishes and destroys all the assets, the BluetoothGattCallback still continues to receive notifications behind the scenes. First it throws the following NullPointerException:
04-25 22:49:54.392 17280-17293/com.myapp.appinfo D/BluetoothGatt﹕ onClientConnectionState() - status=0 clientIf=8 device=54:4A:16:26:A1:B5
04-25 22:49:54.392 17280-17293/com.myapp.appinfo W/BluetoothGatt﹕ Unhandled exception in callback
java.lang.NullPointerException
at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:168)
at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:71)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
04-25 22:49:54.402 17280-17280/com.myapp.appinfo D/BluetoothManager﹕ getConnectionState()
And then continues to publish onNotify() calls that trigger onCharacteristicChanged() calls even after the app has terminated awile ago:
D/BluetoothGatt﹕ onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb
Any advice on how to properly disconnect from GATT characteristic notifications when exiting from an app?
It seems you can't call these method together. The disconnection callback might arrive later than close() method performed.
You can add mGatt.close(); into onConnectionStateChange callback to close the connection.
https://code.google.com/p/android/issues/detail?id=183108
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With