首页 > 解决方案 > 在 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()在调用下一个特征之前,我需要等待它返回。我如何实现这一目标?

我试过使用runBlockingand GlobalScope.launchinkotlinx.coroutines.experimental.*但我不完全确定它们是正确的。

谢谢,亚当

标签: androidkotlinbluetooth-lowenergy

解决方案


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 循环使这变得很棘手。


推荐阅读