Lit*_*pea 5 android bluetooth bluetooth-lowenergy
Android BLE 特性 getValue 在 API 级别 33 中已弃用,在developer.android中BluetoothGattCharacteristic表示我们可以使用BluetoothGatt#readCharacteristic(BluetoothGattCharacteristic)代替
但当我检查代码时,developer.android 也提到它返回一个布尔值而不是 byteArray BluetoothGatt#readCharacteristic(BluetoothGattCharacteristic)
我可以获得该值的正确方法是什么?
Emi*_*mil 11
在 API <= 32 中:
每个BluetoothGattCharacteristic对象都包含一个value字段,该字段会被应用程序(写入时)和蓝牙堆栈(读取/接收通知时)更改。
要写入特征值,首先设置字段value(通过使用setValuesetter 方法),然后通过调用 执行实际写入writeCharacteristic。
要读取特征值,请调用readCharacteristic(这会触发对远程设备的读取请求),并在响应到达时调用的回调中,通过获取字段(通过调用getter 方法)onCharacteristicRead来检索值。valuegetValue
当使用 接收通知或指示时onCharacteristicChanged,以与读取回调中相同的方式检索值。
请注意,getValue仅返回存储在对象value的本地字段中的任何当前值BluetoothGattCharacteristic。它不会触发对远程设备的新读取请求。通常,getValue除非立即在onCharacteristicChanged或onCharacteristicRead回调中调用,否则不应调用。
在 API >= 33 中:
新的 API 不使用任何value字段。相反,该值作为参数传递。
要写入特征值,只需调用writeCharacteristic并将该值作为参数传递即可。
要读取特征值,首先调用readCharacteristic. 当响应从远程设备到达时,onCharacteristicRead将使用刚刚读取的值作为参数来调用回调。
当使用 接收通知或指示时onCharacteristicChanged,该值将作为参数传递给该方法。
支持新旧设备的应用程序:
请注意,为新 API 编译的代码在旧设备上运行时将无法正常工作。您会注意到,新的回调重载根本不会被调用。您基本上有两个选择:
super.onCharacteristicChanged(...)等。对于旧设备,将(仅)调用旧的 API 方法,对于新设备,将(仅)调用新的 API 方法。我建议您将主体onCharacteristicChanged(gatt, characteristic, characteristic.getValue());等放在旧的回调 API 方法中,以便手动将数据传递给新的回调,并将所有逻辑放入新的回调 API 方法中。为什么要更新此 API?
考虑当您具有允许通知和写入的特征时的情况。如果 Android 应用程序在通知到达的确切时间写入特征,则将存在有关value特征对象字段的竞争条件,这意味着您可能会写入刚刚通知的值,或者收到刚刚通知的值的通知即将写。新的 API 通过直接将值作为参数传递来解决这个问题。
| 归档时间: |
|
| 查看次数: |
2747 次 |
| 最近记录: |