Android异步任务需要绑定到广播接收器
我有一个后台服务,大约每秒从外部 BT 传感器接收一次数据。该数据进入,并使用广播意图/接收器发送到 UI。实时数据实时显示。目前这一切都运作良好。
我现在需要做但无法弄清楚的事情是:在用户界面上设置一个按钮,以便它开始对来自广播接收器的数据进行计数(大约每秒进入一次 - 但不够一致设置时钟),并在给定的持续时间(例如 10 秒)后停止。每次有新数据进入时,都应将其添加到总数中,然后在 10 秒的持续时间后,UI 应更新总数,并显示一些消息,例如“总数为 31”。
这听起来很简单,但是使用异步任务 - 这似乎是可行的方法 - 一直给我带来麻烦,因为我无法真正将任务设置为运行循环(据我所知),因为循环时间需要依赖于传入的广播收据。
如果不通过异步任务,关于完成此任务的最佳方法有什么想法吗?我想解决方案可能很简单,但我没有看到它。感谢您的帮助!
I have a background service that receives data roughly once per second from an external BT sensor. That data comes in, and gets sent to the UI using a broadcast intent/receiver. The live data is displayed in real time. This all works well right now.
What I need to do now and can't figure out: Have a button on the UI set up so that it starts a count of data coming in from the broadcast receiver (which is coming in roughly every second - but is not consistent enough to set a clock by), and stops after a given duration like 10 seconds. Every time new data comes in, it should be added to the total, and then after the duration of 10 seconds, the UI should be updated with the total, along with some message like "the total was 31".
This sounds easy, but using an async task - which seemed like the way to go - has been giving me trouble since I can't really set the task up to run a loop (afaik) since the looping timing needs to depend on the incoming broadcast receipt.
Any ideas on the best way to accomplish this if not via async task? I imagine the solution might be a simple one, but I'm not seeing it. Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
定时器 和 TimerTask 将帮助您解决计时问题,如果您想全力以赴,您可以使用 ScheduledThreadPoolExecutor。
A Timer and TimerTask would help you with the timing issue and if you wanted to go all out you could implement the timer using ScheduledThreadPoolExecutor.