Android 在特定时间开始运行 JobScheduler

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

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

发布评论

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

>www.elefans.com

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