我正在编写一个应用程序,它会持续监听和检查传感器(几乎所有可用的传感器)并将该数据保存到设备的数据库中。
我需要每隔 X 秒使用该数据进行一些计算,如果计算检查表明是这样,则抛出一个新事件。 我正在考虑请求在使用应用程序时插入设备(关于电池耗尽)。
对于需要进行计算和引发事件的任务,最佳方法是什么?定时器?线程?异步任务?报警管理器?另一种方法?
我想继续获取传感器数据并将它们保存到数据库中,尽管应用程序不在前台......只要应用程序没有被用户停止,它就应该保存这些值。 一种选择是唤醒锁(PARTIAL_WAKE_LOCK,它使 CPU 保持运行)。
我想听听不同的意见。 提前致谢!吉列尔莫。
最佳答案
您可以使用 AlarmManager
设置重复任务(这是 Android 首选的设置 future /重复任务的方式)。要使用 Service
进行计算(如果您认为计算会很昂贵,那么考虑将它们移动到单独的工作线程或使用 IntentService
)。
关于唤醒锁(来自 AlarmManager 引用):
The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.
关于android - 在实时应用程序的后台运行重复任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5773998/