shreyashirday
shreyashirday

Reputation: 900

Handling indications instead of notifications in Android BLE

Using the Bluetooth SIG Application Accelerator code and it does a good job of demonstrating the different concepts of bluetooth low energy. However, it mentions nothing about indications as opposed to notifications. I know that indications need to be acknowledged unlike notifications, and in the code I would do byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE : BluetoothGattDescriptor.DISABLE_INDICATION_VALUE; instead of byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;. Is there anything else I need to do? How exactly do I let the server know that I received the indication as that is required? Is there something I need to add in?

@Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic)
        {

            notification_id++;
            Log.d("BleWrapper","notification count = " + notification_id);
            // characteristic's value was updated due to enabled notification, lets get this value
            // the value itself will be reported to the UI inside getCharacteristicValue
            getCharacteristicValue(characteristic);
            // also, notify UI that notification are enabled for particular characteristic
            mUiCallback.uiGotNotification(mBluetoothGatt, mBluetoothDevice, mBluetoothSelectedService, characteristic);
        }

Upvotes: 12

Views: 11624

Answers (1)

DriesOeyen
DriesOeyen

Reputation: 493

What you describe is sufficient, but there's a slight error.

Indeed, BLE indications need to be acknowledged by the client whereas notifications do not. However, this is handled entirely behind the scenes by Android. Indications are acknowledged by the system as your onCharacteristicChanged callback gets called.

The only difference, which you already found out about, is that you need to enable the right flag in the Client Characteristic Configuration descriptor on the BLE server. For regular notifications, use ENABLE_NOTIFICATION_VALUE. For indications, use ENABLE_INDICATION_VALUE. Note that you disable both by writing DISABLE_NOTIFICATION_VALUE. The DISABLE_INDICATION_VALUE that you mentioned does not exist, as per the documentation!

On the Android side, it's sufficient to use BluetoothGatt#setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) where enable = true. This will work for both notifications and indications. In both cases, your onCharacteristicChanged callback will be used.

(You've probably already figured this out by now, but posting anyway in case someone ends up here via Google.)

Upvotes: 26

Related Questions