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

1

11

I have a service that has one instance of BluetoothGattCallback

public class MyService extends Service {

    private BluetoothGattCallback callback;

    @Override
    public void onCreate() {
            super.onCreate();

            callback = new BluetoothGattCallback() {
                      @Override
                      public synchronized void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                              Log.i("onConnectionStateChanged", "Status " + status);                
                              Log.i("onConnectionStateChanged", "New State " + newState);                
                      }
            };
    }

    // registration of bluetooth adapter and blah blah blah


}

When I start the app, it works fine and the callback only gets called once, but after a couple of tries, it gets called twice.

Sample logs

10-22 13:29:18.731 26944-26961/redacted.lollipop I/onConnectionStateChange: Status 0
10-22 13:29:18.731 26944-26961/redacted.lollipop I/onConnectionStateChange: New State 2
10-22 13:29:18.731 26944-26961/redacted.lollipop I/onConnectionStateChange: Status 0
10-22 13:29:18.731 26944-26961/redacted.lollipop I/onConnectionStateChange: New State 2

More Sample logs

10-22 13:29:48.836 26944-26961/redacted.lollipop I/onConnectionStateChange: Status 8
10-22 13:29:48.836 26944-26961/redacted.lollipop I/onConnectionStateChange: New State 0
10-22 13:29:48.850 26944-30763/redacted.lollipop I/onConnectionStateChange: Status 8
10-22 13:29:48.850 26944-30763/redacted.lollipop I/onConnectionStateChange: New State 0

And it gets called a lot more times the longer the app stays active. How do I prevent this?

Tronna answered 22/10, 2015 at 5:35 Comment(5)
Just put a log in your onCreate method and see before the callback is called, how many times the method is called. I think the issue is with the concept of ServicesValdis
Or check and see how many times you register that receiver you mentioned in the comment below onCreate()Valdis
It's only called once. What I do is invoke the connectGatt method, which is synchronized & locked by the callback itself, e.g. synchronized(callback) { device.connectGatt(getBaseContext(), true, callback, 2); }Tronna
@KevinD. I am facing the same issue on Android OS 8.0 and below versions. I am closing Gatt connection whenever I received BLE disconnect / Bluetooth off / onDestroy callback of ForegroundService, are you able to resolve this issue at your end? If possible can you check Google Issue Tracker link for more details issuetracker.google.com/issues/135215253Madly
@GaneshTikone have a look at the accepted answer - unfortunately I haven't been doing a lot of native development lately.Tronna
G
26

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.

Gentian answered 8/7, 2016 at 23:39 Comment(6)
How did you check for a valid bluetoothGatt object.Spermogonium
Mainly if I still have a pointer to it and its the same bluetooth device. I ended up having to write code to try and use the last one but if that fails use a new one.Gentian
Sorry mate - been absent from the native world for quite a while. I'll accept this as best answer as this is theoretically sound. Unfortunately I'm unable to verify as I've left the company for a long time.Tronna
You are so right !! I was so confused why the onConnectionStateChanged Callback was getting called several times.Cockburn
You are the legend. Thank you so much!Bribery
props for the updated answer, but do we have any consensus in that closing the gatt is the best way to deal with intermediate disconnects? It seems to me sort of wasteful to reestablish a gatt when the intention is to reconnect anyway. Else what was the purpose of the 'connect()' function? Can the gatt be corrupt? other issues that demand closing and making anew?Aruba

© 2022 - 2024 — McMap. All rights reserved.