你可以,但如果你的时间窗口不是那么严格,则不能保证你的任务在几个小时后开始工作,因为打盹模式。如果您想要真正严格的调度 - 使用 AlarmManager.setAndAllowWhileIdle。而且,据我所知,FirebaseJobDispatcher 尚未发布,还有一些未解决的问题。com.google.android.gms:play-services-gcm
在它发布之前,您可以为此目的使用 GCMNetworkManager(来自 Google Play Services )。您的 FirebaseJobDispatcher 代码可能如下所示:
final FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
if (isSyncEnabled) {
Job job = dispatcher.newJobBuilder()
.setService(SyncService.class)
.setTag(TAG)
.setConstraints(isSyncOnlyWiFi ? Constraint.ON_UNMETERED_NETWORK : Constraint.ON_ANY_NETWORK)
.setRecurring(true) // !!!
.setLifetime(Lifetime.FOREVER) //!!!
.setTrigger(Trigger.executionWindow(syncIntervalInSeconds, syncIntervalInSeconds + TIME_WINDOW_IN_SECONDS))
.setReplaceCurrent(true)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.build();
final int result = dispatcher.schedule(job);
if (result != FirebaseJobDispatcher.SCHEDULE_RESULT_SUCCESS) {
// pre handle error
}
对于 GcmNetworkManager:
PeriodicTask task = new PeriodicTask.Builder()
.setService(SyncManagerService.class)
.setTag(TASK_TAG_SYNC_SERVICE)
.setUpdateCurrent(true)
.setPersisted(true)
.setPeriod(period)
.setFlex(flexInSeconds < period ? flexInSeconds : period)
.setRequiredNetwork(wifiOnly ? PeriodicTask.NETWORK_STATE_UNMETERED : PeriodicTask.NETWORK_STATE_CONNECTED)
.build();
GcmNetworkManager.getInstance(context).schedule(task);