How to perform background recurring job using firebase job dispatcher

639 views Asked by At

I have configured the job like following :

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

In JobService class i have modified onstart and onstop method like following:

 @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;
}

But job dispatcher only only worked once , it is not recurring.My question is similar to this question But no solution was given there, so i had to ask again.

1

There are 1 answers

1
hasan On

I don't know if the solutions is ideal is for every case , but it worked for me. 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);
    }
}

And in Activity:

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