WorkManager beginUniqueWork doesn't work as expected

那年仲夏 提交于 2019-12-06 00:51:09

问题


Currently, I'm using WorkManager 1.0.0-alpha02.

def work_version = "1.0.0-alpha02"
implementation "android.arch.work:work-runtime:$work_version" // use -ktx for Kotlin
// optional - Firebase JobDispatcher support
implementation "android.arch.work:work-firebase:$work_version"

I have no problem to execute background worker, by using the following code, when the app quit.

Use enqueue, work as expected

OneTimeWorkRequest oneTimeWorkRequest =
        new OneTimeWorkRequest.Builder(SyncWorker.class)
                .addTag(SyncWorker.TAG)
                .build();

WorkManager workManager = WorkManager.getInstance();

workManager.enqueue(oneTimeWorkRequest);

Since, I would like to avoid more than one SyncWorker running at the same time. I try to use

Use beginUniqueWork, doesn't work

OneTimeWorkRequest oneTimeWorkRequest =
        new OneTimeWorkRequest.Builder(SyncWorker.class)
                .addTag(SyncWorker.TAG)
                .build();

WorkManager workManager = WorkManager.getInstance();

workManager.beginUniqueWork(
        SyncWorker.TAG,
        ExistingWorkPolicy.REPLACE,
        oneTimeWorkRequest
);

SyncWorker is not running at all.

May I know what step I had missed out? Thank you.


回答1:


beginUniqueWork() returns a WorkContinuation object. You need to call enqueue on that WorkContinuation to actually enqueue it with WorkManager:

workManager.beginUniqueWork(
    SyncWorker.TAG,
    ExistingWorkPolicy.REPLACE,
    oneTimeWorkRequest
).enqueue();



回答2:


The answer from @ianhanniballake is of course helpful and correct, but I thought I'd point out that (with a fast-evolving API) there is a new enqueueUniqueWork() method so I guess the OP could now use:

workManager.enqueueUniqueWork(
    SyncWorker.TAG,
    ExistingWorkPolicy.REPLACE,
    oneTimeWorkRequest
);


来源:https://stackoverflow.com/questions/50657520/workmanager-beginuniquework-doesnt-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!