WorkManager OneTimeWorkRequest InitialDelay works

2019-02-20 13:10发布

问题:

I'm facing problem with WorkManager OneTimeWorkRequest setInitialDelay.

It's work fine when app is in forground or in recent list. But When I remove App from recent list everything is messed up.

What I want to achieve ? - I want send notification to user after few hours when some task is pending ,so after some R&D start work using WorkManager because of It's ability to Schedule Tasks without background service limitation.

Now below is code snippet which work till app is not removed from recent:

    Constraints constraints = new Constraints.Builder()
                                .setRequiresBatteryNotLow(true)
                                .build();

    final OneTimeWorkRequest simpleRequest = new OneTimeWorkRequest.Builder(MyWorker.class)
            .setInitialDelay(3, TimeUnit.MINUTES)
            .setConstraints(constraints)
            .addTag("simple_work")
            .build();

    WorkManager workManager = WorkManager.getInstance();

    workManager.beginUniqueWork("simple_work", ExistingWorkPolicy.KEEP, simpleRequest).enqueue();

Worker class

    public class MyWorker extends Worker {
    private NotificationUtils notificationUtils;
    public static final String EXTRA_OUTPUT_MESSAGE = "output_message";

    public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.showNotificationMessage("TITLE", "This is a MESSEAGE",2);

        Data output = new Data.Builder()
                .putString(EXTRA_OUTPUT_MESSAGE, "I have come from MyWorker!")
                .build();

        setOutputData(output);

        return Result.SUCCESS;
    }


}

Problem is After Remove It from recent list It's send notification but after double time which I set. for example I set setInitialDelay 5 minutes but It's work after 10 minutes.

So ,Please guide me what I do wrong or It's not for schedule task at specific time which I set for once. I don't want to keep repeat work after It's done. I'm create just new after finish first OneTimeWorkRequest so It has to work fine as per documented beginUniqueWork.

Library I am using : implementation "android.arch.work:work-runtime:1.0.0-alpha11"

English isn't my native language so pardon me for grammatically mistake:)

回答1:

You problem is not clear though please update latest work manager lib to android.arch.work:work-runtime:1.0.0-beta03

And you can explain me why do u need to enque the unique work ?

workManager.beginUniqueWork("simple_work", ExistingWorkPolicy.KEEP, simpleRequest).enqueue();

try to replace it with workManager.enque(simpleRequest); and let me know if worked