Getting Started With Firebase JobDispatcher for Android

  Programming

On devices that run Android 5.0 or higher, developers can easily schedule jobs using the JobScheduler system service. To support the same functionality on older versions of Android, Google’s recently released a library called Firebase JobDispatcher. In this tutorial, I’ll be showing you how to use the library to schedule simple recurring jobs.

Prerequisites

To be able to follow this tutorial, all you need is a recent version of Android Studio. Additionally, your project must support API levels 9 or higher.

Add Dependencies

To add Firebase JobDispatcher to your project, add the following compile dependency to your app module’s build.gradle file:

compile 'com.firebase:firebase-jobdispatcher:0.5.2'

And then, press Sync Now to update the project.

Defining a Job

To define a new job, you must create a new Java class that is a subclass of the JobService class. In this tutorial, we’ll be creating a recurring job that simply logs the amount of free space available on an Android device. Let’s name the class DeviceSpaceService.

Because JobService is an abstract class, Android Studio should prompt you to override all its abstract methods.

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class DeviceSpaceService extends JobService {

    @Override
    public boolean onStartJob(JobParameters job) {
        // More code goes here
        return false;
    }

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

As you might have guessed, we’ll be doing most of the work inside the onStartJob() method.

To fetch the disk space available on an Android device, you can use an instance of the StatFs class. Make sure that you initialize it with the root directory. Once you’ve created the instance, simply call the getAvailableBlocksLong() method to fetch the free space available.

StatFs statFs = new StatFs(Environment.getRootDirectory().getPath());

Log.i("MY DEVICE SPACE SERVICE",
        "Free space is " +
                (statFs.getAvailableBlocksLong() *
                 statFs.getBlockSizeLong() /
                 1024) +
                " Kb"
);

Like all services, this service too must be declared in the project’s manifest. Additionally, all JobService services must have an intent filter for the action com.firebase.jobdispatcher.ACTION_EXECUTE. For the sake of security, it’s a good idea to set the exported attribute of the service to false.

<service android:name=".DeviceSpaceService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
    </intent-filter>
</service>

At this point, we’ve finished defining the job. So, let’s move on to actually scheduling it.

Scheduling a Job

To schedule a job, you must first create a FirebaseJobDispatcher object. Therefore, add the following code anywhere inside your activity. Usually, the onCreate() method of an activity is a good place for it.

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

As you can see, the constructor of the dispatcher expects a GooglePlayDriver object, which can be created using the activity’s context.

You can now call either the schedule() method or the mustSchedule() method to schedule your job. The only difference between the two is that mustSchedule() requires less error checking. As an argument, both the methods expect a Job instance, which can be created using the newJobBuilder() method. While creating the Job instance, you must specify the subclass of the JobService you created and a tag. You can also tell if your job must occur again and again. Here’s how:

dispatcher.mustSchedule(
    dispatcher.newJobBuilder()
        .setService(DeviceSpaceService.class)
        .setTag("DeviceSpaceService")
        .setRecurring(true)
        .setTrigger(Trigger.executionWindow(5, 30))
        .build()
);

In the above code, you can see that we have specified an execution window of 5 to 30 seconds. This is important because recurring jobs always need an execution window trigger. Of course, if your job is not recurring, you don’t have to set any trigger for it.

When the job is triggered, you will see output that looks like this:

01-03 06:47:47 41/com.progur.firebasetutorial I/MY DEVICE SPACE SERVICE: Free space is 320844 Kb

The tag associated with a job is quite important because you would be using it while cancelling a job.

Conclusion

You now know how to use Firebase JobDispatcher. It is a great way to schedule tasks consistently on almost all versions of Android. However, for it to work, the user’s device must have the Google Play Services app installed. That, of course, is something you don’t really have to worry about these days.

If you found this article useful, please share it with your friends and colleagues!