项目场景:

最近在做安卓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();
	}
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐