Android BLE API: GATT Notification not received

前端 未结 10 1430
执笔经年
执笔经年 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:15

    This one is working for me:

    to notify master device that some characteristic is change, call this function on your pheripheral:

    private BluetoothGattServer server;
    //init....
    
    //on BluetoothGattServerCallback...
    
    //call this after change the characteristic
    server.notifyCharacteristicChanged(device, characteristic, false);
    

    in your master device: enable setCharacteristicNotification after discover the service:

    @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            services = mGatt.getServices();
            for(BluetoothGattService service : services){
                if( service.getUuid().equals(SERVICE_UUID)) {
                    characteristicData = service.getCharacteristic(CHAR_UUID);
                    for (BluetoothGattDescriptor descriptor : characteristicData.getDescriptors()) {
                        descriptor.setValue( BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                        mGatt.writeDescriptor(descriptor);
                    }
                    gatt.setCharacteristicNotification(characteristicData, true);
                }
            }
            if (dialog.isShowing()){
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        dialog.hide();
                    }
                });
            }
       }
    

    now you can check your characteristic value is change, for example onCharacteristicRead function (this also working on onCharacteristicChanged function as well) :

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i("onCharacteristicRead", characteristic.toString());
            byte[] value=characteristic.getValue();
            String v = new String(value);
            Log.i("onCharacteristicRead", "Value: " + v);
    }
    

提交回复
热议问题