O'Reilly logo

Learning Android by Marko Gargenta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Intent Service

Now that we understand how system services work, we can use another service concept to substantially simplify our Updater service. If you recall, our Updater service is an always-on, always-running service that periodically goes to the cloud and pulls down the latest timeline updates. Since by default a service runs in the same thread as the user interface (i.e., it runs on the UI thread), we had to create a separate thread called Updater within the Updater service that is responsible for the actual network connection. We then started this thread in the service’s onCreate() and onStartCommand() methods. We ran it forever until onDestroy() got called. However, our Updater thread would sleep between the updates for some amount of time. All this worked well in Chapter 8, but there’s a simpler way to accomplish this task, shown in Example 13-9.

An IntentService is a subclass of Service and is also activated by a startService() intent. Unlike a regular service, it runs on its own worker thread, so it doesn’t block our precious UI thread. Also, once it’s done, it’s done. This means it runs only once, but we will use an Alarm later to run it periodically. Any call to the intent’s startService() will recreate it.

Unlike a regular service, we don’t override onCreate(), onStartCommand(), onDestroy(), and onBind(), but rather a new onHandleIntent() method. This method is where we want to put our code that goes online and handles the network updates. Also, unlike a regular service, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required