android BLE 4.0 setCharacteristicNotification can not receive data

Problem Description Recently developing android BLE to read and write data

However, writing data to the device is smooth, but when receiving data from the device, it cannot be received by life or death.

 

/**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    
    }

The above writing will not receive data, mainly because mBluetoothGatt.writeDescriptor(descriptor) is added less;

 

Below is the modified code

 

 

   /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
//        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        boolean isEnableNotification =  mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        if(isEnableNotification) {
            List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
            if(descriptorList != null && descriptorList.size() > 0) {
                for(BluetoothGattDescriptor descriptor : descriptorList) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                }
            }
        }
    }

 If this is not the case, if the data cannot be received, it is another possibility that the uuid setting of the characteristic is incorrect.

You can look at boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

returns false or true,

In addition, I will write another article on Bluetooth data reading and writing.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326473585&siteId=291194637