Android BLE BluetoothGatt object remains connected and runs onCharacteristicChanged () even after a call to disconnect ()

I am trying to disable featured notifications as I exit my application. This is how I do 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 displays: Exiting and Unsubscribing: true . So far, so good. Then I try to completely disable the GATT object 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) ); } 

Everything is strange here. The log now displays the following: FINISHING. Connection state=2 FINISHING. Connection state=2 , indicating that BluetoothDevice is still connected.

This is a problem because when an application terminates and destroys all assets, BluetoothGattCallback 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 it continues to publish calls to onNotify (), which cause calls to onCharacteristicChanged () even after the application has already ended:

 D/BluetoothGatt﹕ onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb 

Any tips on how to turn off GATT feature notifications when exiting the app?

+6
source share
1 answer

It seems you cannot name this method together. The disconnect callback may appear later than the close () method.

You can add mGatt.close (); in onConnectionStateChange callback to close the connection.

https://code.google.com/p/android/issues/detail?id=183108

+1
source

Source: https://habr.com/ru/post/985980/


All Articles