gpt4 book ai didi

android - Android 中的 WorkManager 多次执行 do Work()

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:47 25 4
gpt4 key购买 nike

我正在使用 WorkManager 来安排一些任务,但问题是工作管理器在一次调用中多次执行这些任务 { doWork() }。


我正在使用:

'android.arch.work:work-runtime:1.0.0-alpha08'

我试过使用 -alpha07,06,05,04。但我有同样的问题。有时甚至一次执行5-6次


代码如下:

public class MyWorker extends Worker {

@NonNull
@Override
public Result doWork() {

Log.i("CountWorker","0");
sendNotification("Notice", "A notice was sent");
return Result.SUCCESS;

}

这是 Activity

public class MyWorkerActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

final PeriodicWorkRequest pwr = new PeriodicWorkRequest
.Builder(MyWorker.class, 16, TimeUnit.MINUTES)
.setConstraints(Constraints.NONE)
.build();

WorkManager.getInstance().enqueue(pwr);

}
}

这是 Logcat 的结果:

09-24 16:44:35.954 22779-22816/com.simran.powermanagement I/CountWorker: 0
09-24 16:44:35.970 22779-22817/com.simran.powermanagement I/CountWorker: 0
09-24 16:44:35.977 22779-22818/com.simran.powermanagement I/CountWorker: 0

最佳答案

当您排队一个PeriodicWorkRequest时,不会取消您之前已排队的任何现有PeriodicWorkRequest。因此,在您编写应用程序时,每次 Activity 开始时,您都会添加周期性工作请求,从 1 到 2 再到 3 慢慢增加。

您反而想使用 enqueueUniquePeriodicWork() :

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this PeriodicWorkRequest.

代码如下:

final PeriodicWorkRequest pwr = new PeriodicWorkRequest
.Builder(MyWorker.class, 16, TimeUnit.MINUTES)
.setConstraints(Constraints.NONE)
.build();

WorkManager.getInstance().enqueueUniquePeriodicWork(
"my_worker",
ExistingPeriodicWorkPolicy.REPLACE,
pwr);

关于android - Android 中的 WorkManager 多次执行 do Work(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com