Android connectGatt 方法无法连接BLE蓝牙

之前写过ble的连接,但是最近的开发板蓝牙无法连接,但连接老设备还是可行的。
资料发现开发版蓝牙为双模蓝牙,需添入一段以下代码。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
        } else {
            mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        }

运行后解决问题,记录一下。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个简单的 Android BLE 蓝牙连接代码示例: ``` private BluetoothManager bluetoothManager; private BluetoothAdapter bluetoothAdapter; private BluetoothDevice bluetoothDevice; private BluetoothGatt bluetoothGatt; // 初始化 BluetoothManager 和 BluetoothAdapter bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); // 扫描设备并连接 bluetoothAdapter.startLeScan(new UUID[]{MY_UUID}, mLeScanCallback); bluetoothDevice.connectGatt(this, false, mGattCallback); // 扫描设备的回调函数 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { if (device.getAddress().equals(DEVICE_ADDRESS)) { bluetoothDevice = device; bluetoothAdapter.stopLeScan(mLeScanCallback); } } }; // 连接设备的回调函数 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { bluetoothGatt = gatt; // 连接成功,开始发现服务 bluetoothGatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 连接断开 bluetoothGatt.close(); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 发现服务成功,可以开始进行操作 BluetoothGattService service = gatt.getService(SERVICE_UUID); BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID); characteristic.setValue("Hello, BLE!"); gatt.writeCharacteristic(characteristic); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { // 写入特征值成功 } }; ``` 需要注意的是,此示例中的 UUID、DEVICE_ADDRESS、SERVICE_UUID 和 CHARACTERISTIC_UUID 都需要根据实际情况进行替换。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值