android - 在 Kotlin 中制作功能块
问题描述
我很欣赏这可能已经得到解答,但我无法找到适合我的解决方案。
Tl;博士:如何制作功能块?
我有以下用 Kotlin 为 Android API 28 编写的 BLE 相关代码。
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
for (gattService: BluetoothGattService in gatt!!.services) {
for (gattChar: BluetoothGattCharacteristic in gattService.characteristics) {
if (gattChar.uuid.toString().contains(ADC_SAMPLESET_0) && !subscribed_0) {
subscribed_0 = true
gatt.setCharacteristicNotification(gattChar, true)
val descriptor = gattChar.getDescriptor(
UUID.fromString(BleNamesResolver.CLIENT_CHARACTERISTIC_CONFIG)
)
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
}
上面的 if 语句重复多次,以方便订阅多个 BLE 特性。不幸的是,该gatt.writeDescriptor()
函数异步运行。gatt.writeDescriptor()
在调用下一个特征之前,我需要等待它返回。我如何实现这一目标?
我试过使用runBlocking
and GlobalScope.launch
inkotlinx.coroutines.experimental.*
但我不完全确定它们是正确的。
谢谢,亚当
解决方案
该onDescriptorWrite()
方法可能会有所帮助。你应该已经覆盖它了。
尝试以下操作:
private var canContinue = false;
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { //gatt shouldn't be null, so the null-safe ? isn't needed
loopAsync(gatt);
}
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
canContinue = true; //allow the loop to continue once a descriptor is written
}
private fun loopAsync(gatt: BluetoothGatt) {
async { //Run it async
gatt.services.forEach { gattService -> //Kotlin has a handy Collections.forEach() extension function
gattService.characteristics.forEach { gattChar -> //Same for this one
if (gattChar.uuid.toString().contains(ADC_SAMPLESET_0) && !subscribed_0) {
subscribed_0 = true
gatt.setCharacteristicNotification(gattChar, true)
val descriptor = gattChar.getDescriptor(
UUID.fromString(BleNamesResolver.CLIENT_CHARACTERISTIC_CONFIG)
}
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
while(!canContinue); //wait until canContinue becomes true and then continue
}
}
}
}
}
这有点骇人听闻。可能有一种方法可以通过递归来做到这一点,但是嵌套的 for 循环使这变得很棘手。
推荐阅读
- sql - Snowflake 是否等同于 SQL WITH(NOLOCK)
- r - R dplyr 使用条件有效地创建多个列
- javascript - 制表符和上下文菜单双击右键问题
- maven - 如何在发布中配置唯一版本
- javascript - 显示警报后隐藏模型弹出窗口
- sql - 更新 SQL Server 中的特定行和列
- linux - 为什么当我回显时,我的变量会被 BASH 中 for 循环中的下一个字符覆盖?
- python - Python从tweepy返回流数据
- python - 如何使用 Python 脚本(selenium)从 excel 表中提取数据并输入到网站
- c - 为什么编译器不适用于使用 Visual Code 的 C 语言?