如何使用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);

在工作服务类中,我已经修改了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;
}

但是求职者只有一次工作,这不是反复出现的。我的问题与这个问题相似但是没有解决方案,所以我不得不再次问。

我不知道解决方案是否适合每种情况,但对我有用。 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);

相关内容

  • 没有找到相关文章

最新更新