Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin Android Things:将gpiocallback函数迁移到suspendcoroutine函数_Kotlin_Kotlin Coroutines_Android Things - Fatal编程技术网

Kotlin Android Things:将gpiocallback函数迁移到suspendcoroutine函数

Kotlin Android Things:将gpiocallback函数迁移到suspendcoroutine函数,kotlin,kotlin-coroutines,android-things,Kotlin,Kotlin Coroutines,Android Things,按照下图中的示例,我想将带有回调的函数迁移到SuspendeCroutine函数: 1)是否可以将下面的代码转换为SuspendCorroutine?(我问为什么库中可能有保留代码,键入:onGpioEdge和registerGpioCallback。 2)我该怎么做? class ButtonActivity : Activity() { // GPIO port wired to the button private lateinit var buttonGpio: Gpio

按照下图中的示例,我想将带有回调的函数迁移到SuspendeCroutine函数:

1)是否可以将下面的代码转换为SuspendCorroutine?(我问为什么库中可能有保留代码,键入:onGpioEdge和registerGpioCallback。

2)我该怎么做?

class ButtonActivity : Activity() {
  // GPIO port wired to the button
  private lateinit var buttonGpio: Gpio
  // Step 4. Register an event callback.
  private val callback = object : GpioCallback() {
    fun onGpioEdge(gpio: Gpio): Boolean {
      Log.i(TAG, "GPIO changed, button pressed")
      // Step 5. Return true to keep callback active.
      return true
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val manager = PeripheralManager.getInstance()
    try {
      // Step 1. Create GPIO connection.
      buttonGpio = manager.openGpio(BUTTON_PIN_NAME)
      // Step 2. Configure as an input.
      buttonGpio.setDirection(Gpio.DIRECTION_IN)
      // Step 3. Enable edge trigger events.
      buttonGpio.setEdgeTriggerType(Gpio.EDGE_FALLING)
      // Step 4. Register an event callback.
      buttonGpio.registerGpioCallback(mCallback)
    } catch (e: IOException) {
      Log.e(TAG, "Error on PeripheralIO API", e)
    }
  }

  override fun onDestroy() {
    super.onDestroy()
    // Step 6. Close the resource
    if (buttonGpio != null)
    {
      buttonGpio.unregisterGpioCallback(mCallback)
      try {
        buttonGpio.close()
      } catch (e: IOException) {
        Log.e(TAG, "Error on PeripheralIO API", e)
      }
    }
  }

这是一个有趣的想法,但我不确定协同程序是否最适合GPIO


协同路由非常适合于返回值的异步操作,例如API调用。GPIO更像是可以随时发生的al侦听器,它是一种不同类型的回调。我会将其与onClickListeners进行比较,我认为这也不适合用于合作项目。

谢谢。您如何看待库中的保留代码,键入:onGpioEdge和registerGpioCallback>