Firebase JobDispatcher @AndroidMonk
The Firebase JobDispatcher is a library for scheduling background jobs in your Android app. It provides a JobScheduler- compatible API that works on all recent versions of Android (API level 9+) that have Google Play services installed.
Why use Firebase JobDispatcher ?
Running your code in background using services, alarm manager and broadcast receiver is an expensive task and it becomes more expensive from battery and RAM perspective when most of the apps in your mobile does that. So to overcome these issues JobScheduler came into picture which is an API to schedule and manage all your jobs in background easily. But this API runs on API 21+. So Firebase JobDispatcher came which supports all API’s (Min API 9).
Setting up the dependency
To use Firebase JobDispatcher in your code you will need to add dependency to your build.grade (Module app) file.
If you do not have com.google.android.gms:play-services-gcm
in your dependency, add this:
compile 'com.firebase:firebase-jobdispatcher:0.6.0'
otherwise,
compile 'com.firebase:firebase-jobdispatcher-with-gcm-dep:0.6.0'
Check for latest version from here.
Create your own JobService
import android.util.Log;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
/**
* Created by rajat4914 on 01/04/17.
*/
public class ScheduledJobService extends JobService {
private static final String TAG = ScheduledJobService.class.getSimpleName();
@Override
public boolean onStartJob(final JobParameters params) {
//Offloading work to a new thread.
new Thread(new Runnable() {
@Override
public void run() {
codeYouWantToRun(params);
}
}).start();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
public void codeYouWantToRun(final JobParameters parameters) {
try {
Log.d(TAG, "completeJob: " + "jobStarted");
//This task takes 2 seconds to complete.
Thread.sleep(2000);
Log.d(TAG, "completeJob: " + "jobFinished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//Tell the framework that the job has completed and doesnot needs to be reschedule
jobFinished(parameters, true);
}
}
}
Using Firebase JobScheculer
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.RetryStrategy;
import com.firebase.jobdispatcher.Trigger;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleJob(this);
}
public static void scheduleJob(Context context) {
//creating new firebase job dispatcher
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
//creating new job and adding it with dispatcher
Job job = createJob(dispatcher);
dispatcher.mustSchedule(job);
}
public static Job createJob(FirebaseJobDispatcher dispatcher){
Job job = dispatcher.newJobBuilder()
//persist the task across boots
.setLifetime(Lifetime.FOREVER)
//.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
//call this service when the criteria are met.
.setService(ScheduledJobService.class)
//unique id of the task
.setTag("UniqueTagForYourJob")
//don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// We are mentioning that the job is periodic.
.setRecurring(true)
// Run between 30 - 60 seconds from now.
.setTrigger(Trigger.executionWindow(30, 60))
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
//.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
//Run this job only when the network is available.
.setConstraints(Constraint.ON_ANY_NETWORK, Constraint.DEVICE_CHARGING)
.build();
return job;
}
public static Job updateJob(FirebaseJobDispatcher dispatcher) {
Job newJob = dispatcher.newJobBuilder()
//update if any task with the given tag exists.
.setReplaceCurrent(true)
//Integrate the job you want to start.
.setService(ScheduledJobService.class)
.setTag("UniqueTagForYourJob")
// Run between 30 - 60 seconds from now.
.setTrigger(Trigger.executionWindow(30, 60))
.build();
return newJob;
}
public void cancelJob(Context context){
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
//Cancel all the jobs for this package
dispatcher.cancelAll();
// Cancel the job for this tag
dispatcher.cancel("UniqueTagForYourJob");
}
}
If you run this code and fulfill all the constraint conditions you will see you will see 2 logs with time difference of 2000 ms and repeating themselves after every 30–60 secs. And best part is this works even if your app is closed.
Please mark ❤ if you like the blog. In case if you find any mistake please mention that in comment. Stay tuned for more tech blogs.