Running code in the background with IntentService

I recently completed an additions project for the Kangoo Android application project (you can see the project at my projects page). One of the issues the users, specifically the couriers, were having was that when the couriers went online, they had to keep the app on the foreground to stay online. The project was to allow couriers to stay online and receive requests even when they switch apps on their phone and put the Kangoo app in the background.

Below is the screenshot of what the courier mode looks like.

You can click the “GO ONLINE” button to go online

The problem was that if the courier clicked the “GO ONLINE” button and then switched to another app, the courier would go offline and would not be able to accept any more new requests. We wanted to allow this “Online” state to not be switched off even when the app was thrown into the background and until the user specifically turned the online status to be offline.

The way I approached this problem was with Services, specifically IntentServices, which are essentially background jobs that run that you can start with an intent. Since I come primarily from a web development background, the best analogy I can think of is a cron job that run on specific intervals that are fired by a specific user event.

At first, I tried implementing this with a plain old Service, but quickly found out that it wasn’t meeting my needs. I learned about the IntentService and realized that it was the correct solution to the problem I was trying to solve.

Services in Android, broadly speaking, is a way to set up background operations without the need to interact directly with the user. Services can be used with something like SyncAdapters to perform operations in the background, like syncing user data. IntentService is the same thing as a service, except in that it is started and stopped specifically by a user action. For the problem at hand, which is to keep the user online even when he/she switches into another app, would be to utilize an IntentService rather than a normal Service.

To initialize an IntentService, the code looks something like this (this isn’t the exact code in the Kangoo app, for copyright purposes)

The important bit of the above gist is the onHandleIntent portion of the class. This is where you will move your old code that used to run in the foreground.

And then to start and stop the service

And finally (or you should do this in the beginning), you need to register your service in your AndroidManifest.xml file. I forgot to do this and spent an hour debugging 😐

Relatively simple right?

About the Author Chris Jeon

Software developer currently focusing on Android development.