一种等待传感器数据的方法
我有一个类,它在启动时启动传感器侦听器。当事件触发时,此侦听器将最新的传感器值写入变量。该类继续执行一些逻辑,并在某个时刻检查此变量并根据值继续操作。
我的问题是,无法保证读取变量时有任何值,因为 Android 传感器侦听器仅在传感器值更改时触发事件(并且不一定在启动后立即触发事件)。
因此,我需要我的应用程序等待事件触发,以便它有数据可以处理(最好有超时,以确保它不会无限期地等待)。
我的问题是,实现这种等待的最佳方法是什么?我是否应该有一个处理程序在继续之前每 X 毫秒检查一次值?我是否应该在侦听器和处理程序之间传递某种消息来告诉它数据何时被写入,并且现在可以恢复?还有其他更好的选择吗?
编辑:我应该指出,类逻辑是在 UI 线程上执行的。
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.
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).
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).
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?
EDIT: I should point out, the class logic is executed on the UI thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在使用处理程序来处理完全相同的情况。
I am using Handler for exactly same situation.
这与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:
Then cosumer thread will wait until timeout ocurs or hell frozes out or producer thread issues:
(read documentation)
Your service listener will be producer.