Can i use Firebase JobDispatcher for triggering time specific tasks

瘦欲@ 提交于 2019-12-25 08:52:22

问题


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:


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);


来源:https://stackoverflow.com/questions/39909371/can-i-use-firebase-jobdispatcher-for-triggering-time-specific-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!