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

查看:302
本文介绍了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),并告诉了使用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天全站免登陆