Android BLE API: GATT Notification not received

前端 未结 10 1424
执笔经年
执笔经年 2020-11-29 16:31

Device used for testing: Nexus 4, Android 4.3

Connection is working fine but the onCharacteristicChangedMethod of my callback is never called. However I

10条回答
  •  半阙折子戏
    2020-11-29 17:21

    Here's a simple way to do it, but let me know if you see any drawbacks.

    Step 1 Declare boolean variables

    private boolean char_1_subscribed = false;
    private boolean char_2_subscribed = false;
    private boolean char_3_subscribed = false;
    

    Step 2 subscribe to the first characteristic in the onServicesDiscovered callback:

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!char_1_subscribed)
            subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_1)); char_1_subscribed = true;
    }
    

    Step 3

    Subscribe to any others after the onCharacteristicChanged callback fires

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        if(UUID_CHAR_1.equals(characteristic.getUuid()))
        {
            if(!char_1_subscribed)
                subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_2)); char_2_subscribed = true;
        }
        if(UUID_CHAR_2.equals(characteristic.getUuid()))
        {
            if(!char_3_subscribed)
                subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_3)); char_3_subscribed = true;
        }
    }
    

提交回复
热议问题