android - 在实时应用程序的后台运行重复任务

标签 android real-time alarmmanager

我正在编写一个应用程序,它会持续监听和检查传感器(几乎所有可用的传感器)并将该数据保存到设备的数据库中。

我需要每隔 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/

相关文章:

java - android audiomanager 中的 MODE_IN_COMMUNICATION 错误?

Android:初始化 native AudioRecord 对象时 AudioRecord 错误代码 -20

android - PendingIntent 获取请求代码

java - 如何检测手机是否连接到android auto

android - 如何更改 BottomSheetDialog 中的透明背景?

android - 单击后抽屉导航标题按钮不起作用

netbeans - 是否可以在 Netbeans 7.1 中进行实时共同编辑?

c# - Microsoft StreamInsight 准备好迎接黄金时段了吗?

database - 针对不断变化的大型数据集发出实时警报

java - calendar.add 在 Android 中无法正常运行