How to Schedule a Task in Android using using FireBase Job Dispatcher?

The Firebase JobDispatcher is a library for scheduling background jobs in your Android app. Refer this link to know more details about the library.

Initial Steps

  1. Start a new project in Android Studio (my version 3.1.4)
  2. Provide the appication name as you wish. Company Domain: for example smredlabs.com.
  3. Check Include Kotlin Support
  4. Click Next and select Empty Activity
  5. Click Finish after providing the activity name
For detailed steps refer: Create New Project

Installation of Firebase JobDispatcher

Add the following to your build.gradle's dependencies section:


implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

Create a Job Service

Create a new Kotlin class "MyJobService" and paste the code below


import android.os.AsyncTask
import com.firebase.jobdispatcher.JobParameters
import com.firebase.jobdispatcher.JobService

class MyJobService : JobService(){

    override fun onStopJob(job: JobParameters?): Boolean {
        if(AsynTaskExample() != null){
            AsynTaskExample().cancel(true)
        }
        return true
    }

    override fun onStartJob(job: JobParameters?): Boolean {
        AsynTaskExample().execute(job)
        return true
    }

    inner class AsynTaskExample : AsyncTask<JobParameters, String, JobParameters>(){
        override fun doInBackground(vararg params: JobParameters?): JobParameters {
            println("Job Started... ")
            return params[0]!!
        }

        override fun onPostExecute(result: JobParameters?) {
            jobFinished(result!!,false)
        }
    }

}

Add the created service to the manifest


<?xml version="1.0" encoding="utf-8"?>
...
<application
        android:allowBackup="true"
        ...
        <activity android:name=".MainActivity">
            ...
        </activity>
        
        <service
            android:exported="false"
            android:name=".MyJobService">
            <intent-filter>
                <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
            </intent-filter>
        </service>

</application>
</manifest>


Final Step - Creating a Dispatcher and scheduling the Job

Add the following code in the MainActivity


...
import com.firebase.jobdispatcher.*
...
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        // Create a new dispatcher using the Google Play driver.
        val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(applicationContext))

        // Scheduling the job
        val myJob = dispatcher.newJobBuilder()
                .setService(MyJobService::class.java) // the JobService that will be called
                .setTag("my-unique-tag")        // uniquely identifies the job
                .setConstraints(Constraint.ON_ANY_NETWORK)
                .setLifetime(Lifetime.FOREVER)
                .setRecurring(true)
                .setTrigger(Trigger.executionWindow(60, 60+60))  // start between 60 and 120 seconds from now
                .setReplaceCurrent(false)
                .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                .build()
        dispatcher.mustSchedule(myJob)
    }
}


The above job is recommended to repeat every 60 seconds[ since we have setTrigger .setTrigger(Trigger.executionWindow(60, 60+60)). ]. But the trigger runs the job approximately when it wants. Doze or any other battery saving mode make any sort of cron job in Android to be executed solely when a maintenance cycle is started.

Code available on Github: Click Here
Email your queries to solutiomagister@gmail.com