Android - Running a background task every 15 minutes, even when application is not running

后端 未结 5 758
灰色年华
灰色年华 2020-12-05 05:35

I need to build a background task that runs every 10/15 minutes (doesn\'t really matter, either is good), even when the application is not running.

How can I accompl

5条回答
  •  渐次进展
    2020-12-05 05:43

    Work manager is actually the best thing to do with periodically repeat, their default is 15 minutes which exactly like you need. Here is an example:

            final PeriodicWorkRequest periodicWorkRequest
                    = new PeriodicWorkRequest.Builder(ApiWorker.class, 15, TimeUnit.MINUTES)
                    .build();
            WorkManager.getInstance().enqueue(periodicWorkRequest);
    

    Where ApiWorker is just the following class:

    public class ApiWorker extends Worker implements iOnApiRequestSuccessful {
    
    public ApiWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }
    
    @NonNull
    @Override
    public Result doWork() {
        return Result.success();
    }
    }
    

    And fill whatever work you want to be done in the doWork() function before the return with success.

    Return.success() makes it inserted to the queue again so it will be repeated every 15 minutes.

提交回复
热议问题