BLE 监听以及MTU浅析

监听

部分BLE程序会采用 descriptors 进行对固定UUID进行监听,例如:
“00002902-0000-1000-8000-00805f9b34fb”,这里采用了查找所有可用的descriptor UUID,对其监听

mInitialized = gatt.setCharacteristicNotification(characteristic, true);
//下面部分,不是必须的
Log.i(TAG,"setCharacteristicNotification : " + mInitialized);
if(mInitialized){
for(BluetoothGattDescriptor descList : characteristic.getDescriptors()){
   BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descList.getUuid());
   Log.i(TAG, "Descriptor Service UUID found : " + descList.getUuid().toString());
   if(descriptor != null){
       Log.i(TAG, "Enable Descriptor Service UUID found : " + descList.getUuid());
       descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
       gatt.writeDescriptor(descriptor);
   }
}

MTU

当你发送byte[] 时,有时候会发现超过20字节后的数据消失了。默认MTU位20字节。所以BLE APP需要手动调节最大包长度

@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
    super.onMtuChanged(gatt, mtu, status);
    Log.d(TAG," onMtuChanged");
    if (BluetoothGatt.GATT_SUCCESS == status) {
        Log.d(TAG, "onMtuChanged success MTU = " + mtu);
    }else {
        Log.d(TAG, "onMtuChanged fail ");
    }
}

public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   super.onServicesDiscovered(gatt, status);
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       gatt.requestMtu(131);
   }
   //need 2s to config
   try {
       sleep(2000);
   } catch (InterruptedException e) {
       e.printStackTrace();
   }
   .......
}

这里将MTU设置为131,注意这里需要2秒让设备加载这个配置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值