Android 在特定时间开始运行 JobScheduler [英] Android start running JobScheduler at specific time

查看:28
本文介绍了Android 在特定时间开始运行 JobScheduler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每天的特定时间启动一个 JobScheduler,并在 3 小时后完成它.

I want to start a JobScheduler at a specific time everyday, and finish it after 3 hours.

我每 20 分钟触发一次工作,持续 3 小时,但在 JobInfo.Builder 类中,没有在确切时间开始工作的选项.

I have the part of triggering the job every 20 min, and for 3 hours, but in JobInfo.Builder class there's no option for starting the job at an exact time.

回顾 JobInfo.Builder 类概述,没有什么可以设置启动 JobScheduler 的时间.

Going over the JobInfo.Builder class overview, there's nothing there that sets the time for starting a JobScheduler.

显然,我不想运行它一整天,并检查时间是否匹配,这会消耗比需要的更多的电池,并且是错误的编程.

Obviously, i don't want to run it for the whole day, and check that the time matches, this will drain more battery than needed, and is bad programing.

我想在我指定的时间发出警报并触发这项工作,但这似乎有点矫枉过正.

 JobInfo.Builder builder = new JobInfo.Builder(NIGHT_SYNC_JOB_ID, 
 new ComponentName(context, NightSyncDataJobService.class));

 //Job starts at 11pm, and ends at 2am. Running every 20 minutes.
 builder.setPersisted(true); //Job scheduled to work after reboot
 builder.setPeriodic(Consts.ONE_MINUTE * 20);

 JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
 jobScheduler.schedule(builder.build());

如果您对该问题有任何其他解决方案,除了触发此 JobScheduler 的 AlarmManger,我们将不胜感激.

If you have any other solution to the issue, beside AlarmManger that triggers this JobScheduler, will be much appreciated.

推荐答案

我是通过以下方式实现的(没有AlarmManager),创建了一个新的Job(有唯一的JOB_ID)code> 显然),并告诉 JobScheduler 使用 setOverrideDeadline() 在未来的某个时间安排它.

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();
    }

确保计算出您想要安排任务的正确时间偏移量,并从 JobScheduler 中删除任何现有的作业 ID.

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.

这篇关于Android 在特定时间开始运行 JobScheduler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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