我想使用新的WorkManager每3小时运行一次定期任务。 创建应用程序时启动的工作程序。 我为此使用了以下代码:
public class ApplicationCommon extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
... some init code
// some code that I don't want to run again for every periodic worker...
... some analytics
}
MainActivity内部
@Override
public void onCreate() {
super.onCreate();
runCouponValidatorWorker()
}
fun runCouponValidatorWorker() {
val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = PeriodicWorkRequestBuilder<CouponValidatorWorker>(3, TimeUnit.HOURS).setConstraints(constraints).build()
WorkManager.getInstance()?.enqueueUniquePeriodicWork("couponValidatorWorker", ExistingPeriodicWorkPolicy.REPLACE, worker)
}
但是,工作进程似乎在定期运行时每次都创建Application类的新实例,因此导致许多初始化代码再次运行,就像用户再次运行该应用程序一样(这会导致假阳性分析,API调用等)。有什么方法可以避免/拥有一个指示应用程序是由工作人员启动的标志的?
答案 0 :(得分:0)
Refer to this PeriodicWorkRequest GitHub demo and update TimeUnit as per your requirement (i.e. 3-hour) in DayIncrementViewModel.java. It will work as per your need.
To check whether your work is initiated or not you can store UUID in session when you schedule work request. If UUID is null or blank then your WorkRequest is not initiated.
You can also check Work Status using that UUID. Check this link for more detail.
The Demo is in Java but you can convert your code in Kotlin.
FYI: WorkManager 1.0.0-alpha05 is release now so you should update the WorkManager version because some issues related to PeriodicWorkRequest are fixed in it.