安卓BLE蓝牙开发设置MTU的坑点

项目场景:

最近在做安卓BLE蓝牙开发,连接硬件蓝牙模块,原先也没做过,不断查资料写,也是遇到个坑点,特此记录一下(得再仔细);


问题描述

BLE连接,设置MTU,方便快速收发数据,但发现设置完之后,反而收不到数据了

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            //getUUID(gatt.getServices());
            
            if (status == BluetoothGatt.GATT_SUCCESS) {
                gatt.requestMtu(90);
                setBleNotification();
            }
        }
    	public void setBleNotification() {
	        if (mBluetoothGatt == null) {
	            sendBleBroadcast(ACTION_CONNECTING_FAIL);
	            return;
	        }
	
	        // 获取蓝牙设备的服务
	        BluetoothGattService gattService = mBluetoothGatt.getService(SERVICE_UUID);
	        if (gattService == null) {
	            sendBleBroadcast(ACTION_CONNECTING_FAIL);
	            return;
	        }
	
	        // 获取蓝牙设备的特征
	        BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(CHARACTERISTIC_READ_UUID);
	        if (gattCharacteristic == null) {
	            sendBleBroadcast(ACTION_CONNECTING_FAIL);
	            return;
	        }
	
	        // 获取蓝牙设备特征的描述符
	        BluetoothGattDescriptor descriptor = gattCharacteristic.getDescriptor(DESCRIPTOR_UUID);
	        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
	        mBluetoothGatt.readCharacteristic(gattCharacteristic);
	        logger.info("获取特征值read: "+"----"+ICApplication.sdf.format(new Date())+"  \r\n");
	        if (mBluetoothGatt.writeDescriptor(descriptor)) {
	            logger.info("获取特征值write: "+"----"+ICApplication.sdf.format(new Date())+"  \r\n");
	            // 蓝牙设备在数据改变时,通知App,App在收到数据后回调onCharacteristicChanged方法
	            mBluetoothGatt.setCharacteristicNotification(gattCharacteristic, true);
	        }
    	}

原因分析:

最后查资料,看别人的说法,是因为我设置完MTU后,接着去writeDescriptor,setCharacteristicNotification,会阻塞,具体原理还不清楚


解决方案:

在设置完MTU,在回调方法里判断成功后再去做其他操作,总之这样改完之后,连接收发功能一切正常,满足我需要的。

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    //getUUID(gatt.getServices());

    if (status == BluetoothGatt.GATT_SUCCESS) {
        gatt.requestMtu(90);

    }
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
	if(status == BluetoothGatt.GATT_SUCCESS){
		setBleNotification();
	}
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值