做ble死活连不上,一开始以为bluetoothAdapter.getRemoteDevice(DEVICE_MAC_ADDRESS)这个函数不可靠,结果换成扫描方式找到device,发现还是连接不上。
经历了多次尝试终于发现是因为
bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE);我多了第四个参数,发现安卓官方也是用三个参数的,我信了gpt的鬼话害我连不上。
最后发现连上了但是没有通知数据
查了资料发现
BluetoothGattService service = bluetoothGatt.getService(NOTIFY_SERVICE_UUID); BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID); bluetoothGatt.setCharacteristicNotification(characteristic, true); List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors(); // 遍历设置 BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE 值 , 并写出 for(BluetoothGattDescriptor descriptor : descriptors) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); bluetoothGatt.writeDescriptor(descriptor); }加上加粗代码就行了