如何使用firebase作业调度程序执行后台重复作业

时间:2017-09-10 17:21:43

标签: android firebase-job-dispatcher

我已将工作配置如下:

FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(InfoJobService.class)
            .setRecurring(true)
            .setTrigger(Trigger.executionWindow(0, 10))
            .setLifetime(Lifetime.FOREVER)
            .setTag("data")
            .setReplaceCurrent(true)
            .setConstraints(Constraint.ON_ANY_NETWORK)
            .build();
    dispatcher.mustSchedule(myJob);

在JobService类中,我修改了onstart和onstop方法,如下所示:

 @Override
public boolean onStartJob(JobParameters job) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            uploadDatToFirebase();
        }
    }).start();
    return true;
}
@Override
public boolean onStopJob(JobParameters job) {
    return true;
}

但是,工作调度员只工作过一次,不会再发生。我的问题类似于this question 但那里没有解决方案,所以我不得不再问一次。

1 个答案:

答案 0 :(得分:1)

我不知道解决方案是否适用于所有情况,但它对我有用。 的 JobService:

@Override
public boolean onStartJob(final JobParameters job) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            uploadDatToFirebase(job);
        }
    }).start();

    return true;
}



@Override
public boolean onStopJob(JobParameters job) {
    return false;
}

private void uploadDatToFirebase(final JobParameters parameters) {
    try{
        doSomething();
        Thread.sleep(2000);
    }catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        jobFinished(parameters, true);
    }
}

活动:

 FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));

    Job myJob = dispatcher.newJobBuilder()
            .setService(InfoJobService.class)
            .setTag("InfoJobService")
            .setRecurring(true)
            .setTrigger(Trigger.executionWindow(30, 60))
            .setLifetime(Lifetime.FOREVER)
            .setReplaceCurrent(false)
            .setConstraints(Constraint.ON_ANY_NETWORK, Constraint.DEVICE_CHARGING)
            .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
            .build();

    dispatcher.mustSchedule(myJob);