Cover by Marko Gargenta

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

UpdaterService

As mentioned in the introduction to this chapter, we need a service to run as an always-on background process pulling the latest Twitter statuses into a local database. The purpose of this pull mechanism is to cache updates locally so our app can have data even when it’s offline. We’ll call this service UpdaterService.

Steps to creating a service are:

  1. Create the Java class representing your service.

  2. Register the service in the Android manifest file.

  3. Start the service.

Creating the UpdaterService Java Class

The basic procedure for creating a service, as with activities and other main building blocks, is to subclass a Service class provided by the Android framework.

To create the new service, we need to create a new Java file. Go ahead and select your Java package in the src folder, right-click and choose NewClass, and type in “UpdaterService” as the class name. This will create a new UpdaterService.java file as part of your package.

You may recall from Services that a typical service goes through the life cycle illustrated in Figure 8-1.

Service life cycle

Figure 8-1. Service life cycle

Next, we want to override some of the main life cycle methods:

onCreate()

Called when the service is created for the first time

onStartCommand()

Called when the service is started

onDestroy()

Called when the service is terminated

To do that, you can use Eclipse tool SourceOverride/Implement Methods and select those three ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required