Can i use Firebase JobDispatcher for triggering ti

2019-09-07 06:39发布

I am developing an application where certain tasks as to be done in background at a specific time.

Android developer docs suggests various methods. I know AlarmManager can be used for this purpose. But, I think, using AlarmManager in Android 6.0 in Doze mode will give improper triggers.

I came across JobScheduling libraries from developer docs

As my application supports version below Android 5.0. I thought of using FireBaseJobDispatcher.

Can I use FirebaseJobDispatcher for trigger a specific task at a specific time.

For Example : I want to update the DB once every hour from 9AM to 6PM

1条回答
疯言疯语
2楼-- · 2019-09-07 07:11

You can, but if you time window is not so strict, there is no guarantee that your task start to work in a few hours later, because Doze mode. If you want really strict scheduling - use AlarmManager.setAndAllowWhileIdle. And, as I know FirebaseJobDispatcher has not released yet, and there is a few unresolved issues. Before it releases, you can use GCMNetworkManager (from Google Play Services com.google.android.gms:play-services-gcm) for this purpose. Your code for FirebaseJobDispatcher may looks like this:

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
    }

For 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);
查看更多
登录 后发表回答