Android Tutorial

(avery) #1
Android Tutorial 429

appropriate permissions. For example, a Magic Eight Ball
application might have an underlying service that can receive yes-
or-no questions and provide Yoda-style answers. Any interested
application could connect to the Magic Eight Ball service, ask a
question (“Will my app flourish on the Android Market?”) and
receive the result (“Signs point to Yes.”).The application can then
disconnect from the service when finished using the
Context.unbindService() method.

Creating a Service

Creating an Android service involves extending the Service class
and adding a service block to the AndroidManifest.xml permissions
file. The GPXService class overrides the onCreate(), onStart(),
onStartCommand(), and onDestroy() methods to begin
with. Defining the service name enables other applications to start
the service that runs in the ackground and stop it. Both the
onStart() and onStartCommand() methods are essentially the
same, with the exception that onStart() is deprecated in API Levels
5 and above. (The default implementation of the
onStartCommand() on API Level 5 or greater is to call onStart()
and returns an appropriate value such that behavior will be
compatible to previous versions.) In the following example, both
methods are implemented.

For this example, we implement a simple service that listens for
GPS changes, displays notifications at regular intervals, and then
provides access to the most recent location data via a remote
Free download pdf