Android start running JobScheduler at specific time

ぃ、小莉子 提交于 2019-11-30 07:11:27

I achieved it in the following way (without AlarmManager), created a new Job (with a unique JOB_ID obviously), and told the JobScheduler to schedule it for sometime in the future using setOverrideDeadline().

Here's a snippet which might be helpful:

private JobInfo getJobInfoForFutureTask(Context context,
                                        long timeTillFutureJob) {
        ComponentName serviceComponent = new ComponentName(context, SchedulerService.class);

        return new JobInfo.Builder(FUTURE_JOB_ID, serviceComponent)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE)
                .setOverrideDeadline(timeTillFutureJob)
                .setRequiresDeviceIdle(false)
                .setRequiresCharging(false)
                .setPersisted(true)
                .build();
    }

Make sure to calculate the correct time offset at which you want to schedule the task and also remove any existing Job IDs from the JobScheduler.

adding setMinimumLatency on jobInfo with the deference of the current time and the target time solves this issue.

JobInfo jobInfo = new JobInfo.Builder(1, componentName)
                .setPersisted(true)
                .setBackoffCriteria(6000, JobInfo.BACKOFF_POLICY_LINEAR)
                .setMinimumLatency(1000 * 60)
                .build();

for the example above the scheduler will work after 60 secs.

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