Android在特定时间开始运行JobScheduler

编程入门 行业动态 更新时间:2024-10-20 03:54:04
本文介绍了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

本文发布于:2023-11-27 08:18:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   在特定   Android   JobScheduler

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!