当前位置: 代码迷 >> 综合 >> android BLE 4.0 setCharacteristicNotification接收不到数据
  详细解决方案

android BLE 4.0 setCharacteristicNotification接收不到数据

热度:57   发布时间:2023-10-18 01:06:46.0

问题描述 最近在开发android BLE  读写数据

但是向设备写数据很顺利,但是在接收设备传来的数据时,死活接收不到.

 

Java代码 

 

  1. /** 
  2.     * Enables or disables notification on a give characteristic. 
  3.     * 
  4.     * @param characteristic Characteristic to act on. 
  5.     * @param enabled        If true, enable notification.  False otherwise. 
  6.     */  
  7.    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,  
  8.                                              boolean enabled) {  
  9.        if (mBluetoothAdapter == null || mBluetoothGatt == null) {  
  10.            Log.w(TAG, "BluetoothAdapter not initialized");  
  11.            return;  
  12.        }  
  13.        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);  
  14.      
  15.    }  

上面这样写 是收不到数据的 ,主要是少加了mBluetoothGatt.writeDescriptor(descriptor);

 

下面是修改后的代码

 

 

 

Java代码 

 

  1.    /** 
  2.      * Enables or disables notification on a give characteristic. 
  3.      * 
  4.      * @param characteristic Characteristic to act on. 
  5.      * @param enabled        If true, enable notification.  False otherwise. 
  6.      */  
  7.     public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,  
  8.                                               boolean enabled) {  
  9.         if (mBluetoothAdapter == null || mBluetoothGatt == null) {  
  10.             Log.w(TAG, "BluetoothAdapter not initialized");  
  11.             return;  
  12.         }  
  13. //        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);  
  14.         boolean isEnableNotification =  mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);  
  15.         if(isEnableNotification) {  
  16.             List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();  
  17.             if(descriptorList != null && descriptorList.size() > 0) {  
  18.                 for(BluetoothGattDescriptor descriptor : descriptorList) {  
  19.                     descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);  
  20.                     mBluetoothGatt.writeDescriptor(descriptor);  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  

 如果 不是这种 情况接收不到数据就是另外一种可能了characteristic的 uuid设置不对

你可以看下 boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

返回的是false 还是true,

  相关解决方案