在实时应用程序的后台运行重复任务
我正在编写一个应用程序,它不断监听和检查传感器(几乎所有可用的)并将该数据保存到设备的数据库中。
我需要每隔 X 秒使用该数据进行一些计算,如果计算检查是这样,则抛出一个新事件。 我正在考虑请求在使用应用程序时插入设备(关于电池消耗)。
对于需要进行计算并引发事件的任务,最佳方法是什么?计时器?线程?异步任务?报警管理器?另一种方法?
我想继续获取传感器数据并将它们保存到数据库中,尽管应用程序不在前台......只要用户不停止应用程序,它就应该保存这些值。 一种选择是唤醒锁(PARTIAL_WAKE_LOCK,它保持 CPU 运行)。
我想听听不同的意见。 提前致谢!吉列尔莫.
I'm writing an application which is continuously listening and checking the sensors (almost all available) and saving that data into the database in the device.
I need to make some calculations every X second with that data and throw a new event if the calculations check says so.
I'm thinking about requesting to have the device plugged in while using the application (regarding battery drain).
What's the best approach for the task that needs to make the calculations and throw the event? Timer? Threads? AsynkTask? AlarmManager? Another approach?
I want to keep getting sensors data and saving them to the database despite if the application is not on foreground...it should save the values as long as the application is not stopped by the user.
One option for that is wake locks (PARTIAL_WAKE_LOCK, which keeps CPU running).
I'd like to hear different opinions.
Thanks in advance! Guillermo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 AlarmManager 设置重复任务(这是 Android 设置未来/重复任务的首选方法)。要进行计算,请使用
Service
(如果您认为计算会很昂贵,请考虑将它们移动到单独的工作线程或使用IntentService
)。关于唤醒锁(来自 AlarmManager 参考):
You can use
AlarmManager
to setup the repeating tasks (this is the Android prefered way of setting future/repeating tasks). To make the calculations use aService
(if you think calculations are going to be expensive, then think about moving them to a separate worker thread or useIntentService
).Regarding the wake lock (from the AlarmManager reference):
这是我不久前编写的用于记录 CPU 频率的服务的修改片段。它缺少
Application
和Activity
部分,但说明了我如何编写Service
以保持每十秒记录一次。当手机进入深度睡眠时它不会记录,因此如果您想不间断地记录,那么您将需要获取 PARTIAL_WAKE_LOCK ,但请考虑电池寿命将因此严重缩短。This is a modified snippet of a service I wrote to log CPU frequency some time ago. It lacks the
Application
and theActivity
part, but illustrates how I wrote theService
to keep logging every ten seconds. It does not log when the phone goes into deep sleep, so if you want to log without interruptions, then you will need to acquirePARTIAL_WAKE_LOCK
s, but consider that battery life will be severely reduced by that.