How to prevent BluetoothGattCallback from being executed multiple times at a time

别等时光非礼了梦想. 提交于 2019-11-29 05:07:29

One thing to keep in mind is that each time you call

bluetoothDevice.connectGatt(context, true, callback);

It creates a new instance of the bluetoothGatt object. check out the source for this one you will see:

         BluetoothGatt gatt = new BluetoothGatt(context, iGatt, this, transport);
         gatt.connect(autoConnect, callback);

So one tricky thing is that if your device disconnects and you re-connect to it with. connectGatt(context, true, callback); instead of calling connect() on the previous bluetoothGatt instance you will get 2 bluetoothGatt instances that both have a handle to your gatt callback.

Initially I was trying to fix the problem by trying to close and disconnect the bluetoothGatt before reconnecting.

   if (service.bluetoothGatt!=null){
        Log.i("Rides","Closeing bluetooth gatt on disconnect");
        service.bluetoothGatt.close();
        service.bluetoothGatt.disconnect();
        service.bluetoothGatt=null;
    } 

But this did not work well, somehow I would get multiple onConnectionStateChanged callbacks.

I was able to resolve this problem by checking if I has a valid bluetoothGatt object and making sure to call connect() on it if its a reconnection.

---- Updated Answer ----

I have found that its better to call bluetoothGatt.close() inside the onConnectionStateChanged callback. When you issue a disconnect it sends a message to the bluetooth device to request disconnect. Then once it responds you get the callback and close the bluetooth gatt connection. By waiting for the callback and not opening another gatt connection until its fully closed it seems to prevent multiple gatt objects from getting connected to the app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!