Android Peripheral BluetoothGattServerCallback onS

2019-07-24 16:18发布

问题:

So I have a simple Peripheral application that I am coding in Android Studio running on my Samsung S8 mobile phone. I can setup all my BLE Advertisements and Characteristics just fine but when I add my services. I am not seeing expected results when connected from a another Central device (ie. another mobile phone that has an app to discover bluetooth advertisements).

LogCat output from Android Studio:

As per the Log, I can only see 2 default services that are Generic Attribute(1800) and Generic Access (1801) which are the default services for any Gatt server. I feel that I am missing the "onServiceAdded()" callback that is supposed to tell whether the service was indeed added and discoverable.

My code has no errors and the addService() call is successful. My question is why am I not able to get a response back from onServiceAdded()? While other Override functions like onConnectionStateChange() seem to work fine. This seems to be very basic and I looked at tons of examples but cant seem to get this last bit to work. Anyone with a solution or some good references to look at would be greatly appreciated.

回答1:

I had the same issue, and it seems like callback is not called when a client(Center) was previously connected when the GATT server was restarting.

If you disconnect all the clients and restart the server(peripheral) from clean state, you will see the callback working(in my case, even with 2 services added).

My server is Samsung Galaxy S7(Android 8.0) as well. Client was Android 7 devices.

(In addition to this callback issue:) There is some caching or strange thing going on, and if you had previous connection it does not work well with multiple services(one predefined and one custom). In my case, when a client was already connected and if I add more than 1 service to the server when starting, gattServer.getService(uuid) was returning null. Adding one service was ok.



回答2:

I hade the same issue (Nokia 6.1) where onServiceAdded was called only once although I was adding 2 services and I was getting randomly

onCharacteristicReadRequest() no char for handle nnn

when trying to connect from another device.

I found a relevant point in the documentation https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#addService(android.bluetooth.BluetoothGattService)

The BluetoothGattServerCallback.onServiceAdded(int, BluetoothGattService) callback will indicate whether this service has been added successfully. Do not add another service before this callback.

The reliable solution I found was to add one service, wait for onServiceAdded to be called, then add the second service, wait for onServiceAdded again and then I call startAdvertising.