我使用以下代码使每次有可用的互联网时运行作业。另外,我想要的是,在触发服务后(由于可用连接(,只要有互联网,我希望该服务继续定期(每 30 秒(运行 g,然后当连接不再可用时,服务应该停止,只有在下次有互联网时恢复。
FirebaseJobDispatcher jobDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(MainActivity.this));
.setTag("JobService")
.setRecurring(true)
.setLifetime(Lifetime.FOREVER)
.setService(JobService.class)
.setTrigger(Trigger.executionWindow(0,10))
.setReplaceCurrent(true)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL);
builder.addConstraint(Constraint.ON_UNMETERED_NETWORK);
jobDispatcher.mustSchedule(builder.build());
我想让 JobService 本身在下次运行时(三十秒内(进行调度,在时间结束后,测试是否有互联网,然后好吧,否则我会调用 Onstop 方法,但它感觉不像是解决这个问题的正确方法。
写: setTrigger(Trigger.executionWindow(30,40))
. 解释:Firebase Job Dispatcher GitHub
Scheduling a more complex job
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(false)
// don't persist past a device reboot
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
或者对于 executionWindow,规则是:
.setTrigger(Trigger.executionWindow(
INTERVAL_IN_SECONDS,
INTERVAL_IN_SECONDS + TIME_WINDOW_IN_SECONDS
))
参考: https://stackoverflow.com/a/39909986/1537413