Create background task using JobIntentService

Services are used in Android to perform long running tasks like downloading files or images from the server, playing or streaming music. Services do not have any UI component as they do not have any user interaction. The main objective of services is to get work done in the background. Android SupportLib v26.0.0 released JobIntentService for background task processing and to save device resources like RAM and battery. JobIntentService provides same functionality as IntentService but uses Jobs instead of Services in devices running Android 8 and above. Although JobIntentService uses the old services in devices below 8.0.

Another advantage of using JobIntentService is you don’t have to manage wake lock. JobIntentService do not require WakefulIntentService. Though you need to add  “android.permission.WAKE_LOCK” permission if you are targeting API below 26.

Adding JobIntentService to your project:

Add Google repository in projects build.gradle file

 

In app build.gradle file add

In AndroidManifest.xml file register JobIntentService inside the application tag.

Now let’s see a basic example of using JobIntentService for background task in your app.

To start JobIntentService you can call enqueueWork function to add background work.

How to communicate with Activity

Now we have seen how to create our new JobIntentService we may need to communicate with the activity. If there is a need to send result back to the activity then we can use ResultReceiver. ResultReceiver is an interface to receive callback results from anyone. Use resultReceiver by extending ResultReceiver class.

Let’s create our ResultReceiver class.

Activity example

 

 

Leave a Reply

%d bloggers like this: