Android中的WorkManger多次执行doWork() [英] WorkManger in Android is executing doWork() more than once

查看:558
本文介绍了Android中的WorkManger多次执行doWork()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using WorkManager to schedule some tasks but the problem is that work manager is executing those tasks { doWork() } more than once in a single call.

我正在使用:

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

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

I have tried using -alpha07,06,05,04. But I have same issue. Sometimes it even executes 5-6 times at once

这是代码:

public class MyWorker extends Worker {

@NonNull
@Override
public Result doWork() {

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

}


这是活动


This is the 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的结果:

This is the result from 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

推荐答案

enqueue一个PeriodicWorkRequest时,不会取消您先前排队的任何现有PeriodicWorkRequest.因此,在编写应用程序时,每次活动开始时,您都会添加定期的工作请求,并从1逐渐变到2到3.

When you enqueue a PeriodicWorkRequest, that does not cancel any existing PeriodicWorkRequest that you have previously enqueued. Therefore as you have written your app, every time your activity starts, you add yet periodic work request, slowly going from 1 to 2 to 3 onward.

您改为使用 enqueueUniquePeriodicWork() :

You instead want to use enqueueUniquePeriodicWork():

此方法允许您加入唯一名称为PeriodicWorkRequest的队列,其中一次只能激活一个具有特定名称的PeriodicWorkRequest.例如,您可能只希望一个同步操作处于活动状态.如果有一个未决,您可以选择让其运行或将其替换为新工作. uniqueWorkName唯一标识此PeriodicWorkRequest.

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中的WorkManger多次执行doWork()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆