[英]How to process Android sensor events with Kotlin Coroutines?
我想以面向流的方式处理 Android 上的传感器事件,最好使用 Kotlin 的协程。
对于传感器,我知道如何使用public void onSensorChanged(SensorEvent event);
实现回调接口SensorEventListener
;
我怎样才能将数据发送到kotlinx.coroutines.channels.Channel
呢?
您可以简单地让协程为您将事件放入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
}
}
}
您也可以使用 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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.