我想安排每晚数据库更新。所以我使用新的Android WorkManager。我的理解是,一旦安排它将始终在后台独立于应用程序的生命周期运行。 是对的吗?我的第一次测试表明只有在应用程序运行时才会执行工作。
val locationWork = PeriodicWorkRequest.Builder(UpdateDatabaseWorker::class.java, 24, TimeUnit.HOURS)
.addTag("DATABASE_UPDATE_SERVICE")
.build()
WorkManager.getInstance().enqueue(locationWork)
答案 0 :(得分:30)
Based on various issues reported on the WorkManager bugtracker, their documentation is not completely precise about the exact behavior of the WorkManager in such edge cases.
On certain devices, apps are force stopped when the app is cleared from task manager, so that part is expected. ... source
Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it's infeasible for us to address it - the problem lies in the OS and there is no workaround. source
The only issue that we have come across is the case where some Chinese OEMs treat swipe to dismiss from Recents as a force stop. When that happens, WorkManager will reschedule all pending jobs, next time the app starts up. Given that this is a CDD violation, there is not much more that WorkManager can do given its a client library. source
To add to this, if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched. source
With intense testing of a OneTimeWorkRequest
(without constraints) on a Pixel 2 XL with stock android the behavior is the following:
答案 1 :(得分:4)
我的理解是,一旦安排它将永远运行在 独立于应用程序生命周期的背景。是吗?
是。基于documentation
即使你的应用程序强制退出,也可以保证任务运行 设备重启。
WorkManager根据设备API级别和应用程序状态等因素选择适当的方式来运行任务。如果WorkManager在应用程序运行时执行您的任务之一,WorkManager可以在您应用程序进程的新线程中运行您的任务。如果您的应用未运行,WorkManager会选择适当的方式来安排后台任务 - 具体取决于设备API级别。
WorkManager可能会使用JobScheduler,Firebase JobDispatcher或AlarmManager,具体取决于API级别。在执行工作之前,它会考虑打盹并更好地限制所有其他约束。在打盹模式下可能会有一些延迟,因为它可能会等待维护窗口。
注意:强>
WorkManager适用于需要保证即使应用程序退出系统也会运行它们的任务,例如将应用程序数据上传到服务器。如果应用程序进程消失,它不适用于可以安全终止的进程内后台工作;对于这种情况,我们建议使用ThreadPools。
答案 2 :(得分:1)
这就是文档所说的:
注意:WorkManager适用于需要保证系统即使应用程序退出也会运行它们的任务,例如将应用程序数据上传到服务器。如果应用程序进程消失,它不适用于可以安全终止的进程内后台工作;对于这种情况,我们建议使用ThreadPools。
但必须有一些条件。 如果满足条件,那么WorkManager将运行任务(这很重要)。条件类似“仅在设备充电和在线时”
阅读此carefully, WorkManager会尝试按您要求的时间间隔运行您的任务,受您施加的限制及其他要求。 < / p>
在这里,我找到了一个关于如何使用WorkManager来安排任务的好教程:https://android.jlelse.eu/how-scheduling-work-with-new-android-jetpack-component-workmanager-852163f4825b