问题描述
我有一类在启动时它启动传感器监听器。此侦听器写入最新的传感器值给一个变量时,事件被触发。类接着做一些逻辑,并在某些时候,会检查这个变量,并继续取决于值。
I have a class which initiates a sensor listener when it is started. This listener writes the latest sensor value to a variable when an event is triggered. The class goes on to do some logic, and at some point, will check this variable and proceed depending on the value.
我的问题是,有没有保证,还有就是当变量是只读的,因为Android的传感器听众只有触发事件的任何值时,传感器值的变化(而不一定是尽快为他们开始触发事件)
My issue is that there's no guarantee that there is any value when the variable is read, since Android sensor listeners only trigger an event when the sensor value changes (and don't necessarily trigger an event as soon as they are started).
因此,我需要我的应用程序等待一个事件的触发,使其有数据要工作过(preferably了超时,以确保它不会无限期地等待)。
Thus, I need my app to wait for an event to trigger so that it has data to work off (preferably with a time-out, to ensure that it doesn't wait indefinitely).
我的问题是,什么是实现这个等待的最好方法是什么?我应该有一个处理程序,检查每X毫秒,然后再继续的值?我应该有某种消息的监听器和处理程序告诉它,当数据被写入之间传递的,而且它现在可以恢复?是否还有其他选择哪个更好?
My question is, what's the best way to implement this wait? Should I have a handler that checks every X milliseconds for a value before proceeding? Should I have some sort of message passing between the listener and the handler to tell it when data has been written, and that it can now resume? Are there other options which are better?
干杯。
编辑:我应该指出,类逻辑是在UI线程上执行
I should point out, the class logic is executed on the UI thread.
推荐答案
这是不严格相关的Android,而且一般的Java问题。机制来实现,这是容器java.lang.Oject。假设你有一些护卫对象,在生产者和消费者线程访问。在消费者线程调用:
This is not strictly related to android, but also general java question. Mechanism to implement this is container in java.lang.Oject. Assuming you have some guard object, where producer and consumer threads have access. On consumer thread you call:
guard.wait(some_optional_delay_Look_into_javadoc);
然后cosumer线程将等到超时ocurs还是地狱弗罗泽出或生产线的问题:
Then cosumer thread will wait until timeout ocurs or hell frozes out or producer thread issues:
guard.notify[All]();
(阅读文档)
(read documentation)
您服务监听器将是生产商。
Your service listener will be producer.
这篇关于一种等待传感器数据的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!