What are the steps to get notified by Bluetooth Low Energy (BLE) device?

后端 未结 4 984
慢半拍i
慢半拍i 2021-01-31 12:20

I am working on a Bluetooth Low Energy (BLE) app. I have a BLE device (scale) which measures weight. I am able to connect with this device. But I am not getting how to read data

4条回答
  •  南旧
    南旧 (楼主)
    2021-01-31 13:11

    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 :

    @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);
    }
    

提交回复
热议问题