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
onStartCommand() methods. We ran
it forever until
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.
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
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, ...