Skip to content

JobIntentService is your saviour!


IntentService.class
is an extensively used service class in Android because of its simplicity and robust in nature. Since the release of Oreo, made things more difficult for developers to use this class in a full swing for their applications. For those who are relied on IntentService class, from oreo onwards you cannot simply use this class. I was also searching for an exact and efficient alternative for this class so that I can change old intentservice class to that. The search ended up in JobIntentService which is exactly does the same job of IntentService by using new Job APIs of oreo. This class is available in the support library of SDK 26.

Implementation of JobIntentService class is a simple process. Also, You can easily migrate from IntentServiceClass to JobIntentServiceClass.For device targeting SDK 26 or later, This class’ works are dispatched via JobScheduler class and for SDK 25 or below devices, It uses Context.startService() (Same as in IntentService). First, compile the dependency on your app level gradle.

compile 'com.android.support:support-compat:27.0.0'

Now create a class file which extends JobIntentService.Java class. Implement the overridden method.

/**
* JobIntentClass written in Kotlin
**/

class MyApiService : JobIntentService() {

//Constant ID to recognise the job

val JOB_ID = 1000


fun enqueueWork(context: Context, work: Intent) {

    enqueueWork(context, FirebaseApiService::class.java, JOB_ID, work)
}

override fun onHandleWork(intent: Intent) {

        //do your work here.
}

The static method called enqueueWork(Context context, Intent work) is the convenience method used for enqueuing the work. Every service will have a unique ID which is defined by you. Here is a full gist of a sample service class.

 

 

While dozing on the device, Service will be subject to normal policies of a Job class ie, The job will get delayed or will not run. This is applicable to Oreo on later devices. But in pre oreo Android devices, The service will run under normal conditions but it is more likely to kill on memory pressure situations. While running on post Oreo devices, you do not need to take care of WakefulBroadcastRecievers. They are handled by the system itself.

Happy coding!

Published inAndroid

3 Comments

  1. Way cool! Some very valid points! I appreciate you penning this article plus the rest of the site is really good.

  2. Pretty nnice post. I just stumbled upon your blog and
    ԝanted to say that I have really enjoyed surfing around your blog
    posts. After all I’ll be subsсribing to your feed and
    I hope you write gain very soon!

Leave a Reply

Your email address will not be published. Required fields are marked *