推荐一个靠谱的方式在应用关闭后继续运行

Recommend a realiable way to continue running after the app is closed

我正在记录加速度计的输出。

任何人都可以推荐一种可靠的方法来监控应用程序关闭后 onSensorChanged(运行在后台运行应用程序)。

WorkManager
我已经尝试过 WorkManagerWorkManager 仅在应用程序打开时出现在 运行 中。我读到这可能是特定于设备的,因为某些设备会在关闭时强制停止应用程序,或者在应用程序关闭后阻止后台任务执行。

sticky-notifications
我对使用 sticky-notifications 很好奇,尽管这不是我的第一选择。我现在正在研究这个选项。我注意到一些应用程序实现了这个选项。缺点是粘性通知会被视为烦人,用户可能会禁用 sticky-notifications.

其他选项?

如果你想在后台运行,你应该使用服务。但可能 Android 不允许这样做,因为在后台继续收听传感器会消耗太多电池。主要是AndroidP对电池消耗比较严格

在这种情况下,WorkManager 不是正确的解决方案,因为 Worker 的执行限制为 10 分钟,然后被 OS 停止。但是,抛开时间限制,WorkManager 是为其他用例开发的,所以使用类似这样的东西(当你接近 10 分钟限制时使用一些 hack 来重新安排工作人员)似乎与图书馆设计相悖。要了解 WorkManager 旨在解决的用例背后的介绍,您可以查看此博客:Introducing WorkManager.

前台服务是一个选项,但我担心持续监控传感器会对设备的电池寿命产生非常糟糕的影响。有关可用选项的更多信息,以 运行 后台代码,您可以查看此博客:Modern background execution in Android

根据您需要对传感器数据执行的操作,另一种方法是使用 Activity Recognition API:

You can tell the API how to deliver results by using a PendingIntent, which removes the need to have a service constantly running in the background for activity detection purposes. Your app receives the corresponding Intents from the API, extracts the detected activities, and decides if it should take an action.

2021 年 3 月更新

自从我最初写这个答案以来已经有几次更新:

  1. WorkManager v2.3.0 引入了对更长的 Worker 的支持,可以选择使用 setForeground() for CoroutineWorkers and ['setGoregroundAsync()][5] for all kind of Worker`s. This is allows to overcome the 10 minutes limit and is documented in Support for long-running workers.
  2. 将它们“提升”到前台服务
  3. Android 12 计划对 Foreground Services and this has some impact on WorkManager. The new v2.7.0, currently in alpha, is adding the concept of expedite work 进行一些更改,以向后兼容的方式为 Android 12 提供支持。

总的来说,我仍然认为让您的应用程序在后台监控传感器会对设备的电池产生不良影响,您应该寻找替代品。