Android Background Services

Harun Wangereka
5 min readJan 10, 2018

--

I decided to write this article after a long struggle in executing background tasks in android which took me close to a month to find the best way possible to manage the background tasks. I have tried many methods and am going to discuss all my findings so as to help any other android developer who might be stuck in the same problem too.

Methods of executing background tasks

  1. Services
  2. Job scheduler
  3. Firebase job dispacher
  4. Intent Service+ Alarm Manager

Let me give a brief intro for each of the following approaches

Service-A service is a component which runs in the background, without direct interaction with the user. As the service has no user interface it is not bound to the lifecycle of an activity. Services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc.

Intent Service-The IntentService class provides a straightforward structure for running an operation on a single background thread. IntentService runs outside the application in a background process, so the process will run even if your application is closed.

Limitations of the Intent Service

  • You cannot affect the user interface from this background service directly
  • Requests are handled on a single worker thread and processes just one request at a time.
  • You cannot easily cancel an intent service once you start one

Intent Service Vs AsyncTask

A common point of confusion is when to use an AsyncTask and when to use an IntentService. An AsyncTask is tightly bound to a particular Activity. In other words, if the Activity is destroyed or the configuration changes then the AsyncTask will not be able to update the UI on completion. For short one-off background tasks tightly coupled to updating an Activity, we should use an AsyncTask. A good example is for a several second network request that will populate data into a ListView.

IntentService is geared towards longer running tasks that should run in the background, independent of the activity that is currently open and being viewed. The activity can be switched or the app can be paused and the IntentService will still continue to run in the background. For longer running tasks that are independent of a particular Activity, use IntentService.

Job Scheduler - JobScheduler API was introduced in API 21. Before JobScheduler, we had AlarmManager API which is present from Android version 1. Although significant changes were made in this API from version 19, to save battery of the device and boost the performance, the biggest drawback of Alarm Manager is that it solely works on the basis of time. To overcome this drawback, Google introduced JobScheduler which works on various conditions like availability of network, charging of device.

JobScheduler is good news for all the developers whose app have minimum SDK version set to 21 or greater as they can use this API directly. But what about the apps whose minimum SDK is less than 21?. Thankfully there are a couple of options available to the developers.

Firebase Job Dispachter-This library is a wrapper over GcmNetworkManager. But there is one big advantage it holds over GcmNetworkManager. If Google Play Services app is not installed or the app version is less than 7.5, then this library internally uses AlarmManager to schedule the tasks. This can work all the way up to minimum SDK 9. Similar to GcmNetworkManager, this library uses the framework’s JobScheduler if the application is running on Lollipop and above.

Intent Sevice+ Alarm Manager- after weeks of trying to work with services,job scheduler and firebase job dispatcher i resulted to using intent service in combination with alarm manager to handle the background tasks in android which works well under all circumstances.

Why Intent Service+Alarm Manager?

  1. For services is that they run on the main thread and services can be killed anytime the activity that started the service is killed. But for intent service,it runs on the background thread which means that even when the activities are destroyed the intent service will not be destroyed
  2. For job scheduler and firebase job dispatcher they set a task to be executed a time in the future which can fail to work if the at the set time the device if of. For this case(Intent Service+ Alarm Manager) we have the alarm which now triggers the execution of the task at the set time. When the device if off,the task will be queued and will be executed once the device if on. As for alarm manager you can restart the alarms when the device is powered on or rebooted.
  3. Under the hood the intent service uses the handler thread to do the background tasks which saves you the hustle of having to create an AsyncTask to handle the background processes.

AndroidBackgroundServices Demo project

I created a sample project to demonstrate the use of intent service and the alarm manger to create a recurring task.

In this project, i want to display a toast message every 15 minutes.You can add all your complex functionality later after you get the whole concept but so far its for demo purposes. No much UI features. Its just one activity which when created creates an alarm which then triggers the intent service to work. Am going to explain the most significant bits.

Creating an IntentService

First, you define a class within your application that extends IntentService and defines the onHandleIntent which describes the work to do when this intent is executed:

Now we can use this service within our application.

Registering the IntentService

Each service needs to be registered in the manifest for your app:

<application
android:icon="@drawable/icon"
android:label="@string/app_name">

<service
android:name=".BackgroundService"
android:exported="false"/>
<application/>

Notice that we specify this in the manifest file with the name and exported properties set. exported determines whether or not the service can be executed by other applications

Executing The IntentService

In this case we are going to create an alarm which when triggered which start the intent service.

In the above code we create an alarm that repeats every 15 minutes. The ToastBroadcastReceiver is a class which extends BroadCastReceiver. In the OnReceive method of this class is where we start the intent service as below:

Now the service is up and running lets see how we will communicate with the activity so as to send a the response from the intentservice. We are going to use BroadCastReceiver to show the toast messages.The BroadCastReceiver will receive broadcasts from the service as demonstrated above in the intentservice class where we send the broadcast with the message “I’M running after ever 15 minutes”.

Remember the intentservice does not work on the main thread thats why we are using the Broadcast receiver to display the toast message.Everything is almost ready now we have a few things to do with our broad cast receiver. We have to register it in the manifest just like our intent service

<receiver
android:name=".ResponseBroadcastReceiver"
android:process=":remote" >
</receiver>

Note we have two broadcast receivers in our case,make sure all of them are registered in the manifest as shown above.(Note that we need to define android:process=":remote" so that the BroadcastReceiver will run in a separate process so that it will continue to stay alive if the app has closed.Finally lets register the ResponseBroadcastReceiver in our HomeActivity so as to get the toast.

IntentFilter intentFilter= new IntentFilter();
intentFilter.addAction(CallLogService.ACTION);
registerReceiver(broadcastReceiver,intentFilter);

Register the response broadcast receiver in the onCreate method and also in the onResume method. And thats all you have to do.The complete demo project is on github:

I hope this guide helps you. You can also improve on the demo project also as this are only per my findings and its not like a final thing am still on the learning process.

--

--

Harun Wangereka
Harun Wangereka

Written by Harun Wangereka

Google Developer Expert for Android | Android Engineer | Co-organizer droidconKE, Android254 & Kotlin Kenya | Android Author @raywenderlich.com

Responses (4)