android - 用于后台任务的最佳做法是什么?

标签 android background-service android-jobscheduler

我有一个用例,每当事务完成或失败时,我都必须在后台等待(不会卡住 UI)5 分钟,然后在没有用户干预的情况下调用一段代码。所以 AFAIK 我需要为此实现后台服务。

我想知道哪个更适合我的场景。

  1. Workermanager ( JetPack )
  2. Jobscheduler(对于 API 14 - 21,Firebase JobDispatcher)
  3. Intent 服务

在 Oreo 及更高版本中,如果我运行后台服务,它会在通知中显示应用程序正在后台运行吗?

最佳答案

现在推荐的后台处理方式是 Jetpack WorkManager API。出于以下原因,我将引用官方文档:

WorkManager chooses the appropriate way to run your task based on such factors as the device API level and the app state. If WorkManager executes one of your tasks while the app is running, WorkManager can run your task in a new thread in your app's process. If your app is not running, WorkManager chooses an appropriate way to schedule a background task--depending on the device API level and included dependencies, WorkManager might use JobScheduler, Firebase JobDispatcher, or AlarmManager. You don't need to write device logic to figure out what capabilities the device has and choose an appropriate API; instead, you can just hand your task off to WorkManager and let it choose the best option.

In addition, WorkManager provides several advanced features. For example, you can set up a chain of tasks; when one task finishes, WorkManager queues up the next task in the chain. You can also check a task's state and its return values by observing its LiveData; this can be useful if you want to show UI indicating your task's status.

因此,不必每次都担心选择哪个后台处理(因为每个任务都有推荐和合适的方式),您只需使用 WorkManager 即可完成它的工作。

这是考虑到以下陷阱:

WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.

附言由于 WorkManager API 在后台使用 JobScheduler、Firebase JobDistpacher 或 AlarmManager,您必须考虑所用功能的最低 API 级别。 JobScheduler 至少需要 API 21,Firebase JobDispatcher 至少需要 API 14 和 Google Play 服务。

完整文档检查:https://developer.android.com/topic/libraries/architecture/workmanager

关于您的第二个问题:据我所知,您将始终看到该通知,因为它会通知用户您的应用正在耗电。用户可以通过 Android Oreo 8.1 中的设置禁用通知。

关于android - 用于后台任务的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708993/

相关文章:

android - 所有 Activity 中的通用对话框

android - 如何在 Android 中设置应用程序范围的字体?

android - 在 ListView 项目中启动 AnimationDrawable。元素什么时候附加?

background-service - 为什么存在更新 at-startup-background-update-services ?

java - API 级别 10 的 OpenGL Android 教程

android - 计时器任务在 android 中无限期后停止运行

android - 工作管理器是否适合在后台播放音乐?

android - 作业计划程序未在 Android 12 上锁定/直接启动时启 Action 业

android - 从 JobService 观察 LiveData

Android JobScheduler 总是工作 1 分钟