如何使用 Kotlin 协程处理 Android 传感器事件?

mic*_*cgn 1 android coroutine android-sensors kotlin kotlin-coroutines

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

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

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

Sid*_*ria 6

您可以简单地让协程为您添加一个事件,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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)