【问题标题】:How to process Android sensor events with Kotlin Coroutines?如何使用 Kotlin Coroutines 处理 Android 传感器事件?
【发布时间】:2020-05-21 19:41:33
【问题描述】:

我想以面向流的方式处理 Android 上的传感器事件,最好使用 Kotlin 的协程。

对于传感器,我知道如何实现回调接口SensorEventListener public void onSensorChanged(SensorEvent event);

我怎样才能将数据发送到kotlinx.coroutines.channels.Channel

【问题讨论】:

    标签: android kotlin android-sensors coroutine kotlin-coroutines


    【解决方案1】:

    您可以简单地让协程为您将事件放入Channel<SensorEvent>,如下所示。

    object SensorEventProcessor : SensorEventListener {
    
        private val scope = CoroutineScope(Dispatchers.Default)
        private val events = Channel<SensorEvent>(100) // Some backlog capacity
    
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
            // If you need to process this as well, it would be a good idea
            // to wrap the values from this as well as onSensorChanged() into
            // a custom SensorEvent class and then put it on a channel.
        }
    
        override fun onSensorChanged(event: SensorEvent?) {
            event?.let { offer(it) }
        }
    
        private fun offer(event: SensorEvent) = runBlocking { events.send(event) }
    
        private fun process() = scope.launch {
            events.consumeEach {
                // Do something
            }
        }
    }
    

    【讨论】:

    【解决方案2】:

    您也可以使用 channelFlow,它仍然是过期的,但很有希望。

        fun getAccelerometerData(): Flow<FloatArray> {
        if (accelerometer == null) {
            return emptyFlow()
        }
        return channelFlow {
            val listener = object : SensorEventListener {
                override fun onSensorChanged(event: SensorEvent?) {
                    if (event !== null) {
                        channel.offer(event.values)
                    }
    
                }
    
                override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
                    //
                }
            }
            sensorManager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_FASTEST)
    
            awaitClose {
                sensorManager.unregisterListener(listener)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      相关资源
      最近更新 更多