Chapter 11

Developing Android Services


  • How to create a service that runs in the background
  • How to perform long-running tasks in a separate thread
  • How to perform repeated tasks in a service
  • How an activity and a service communicate

A service is an application in Android that runs in the background without needing to interact with the user. For example, while using an application, you may want to play some background music at the same time. In this case, the code that is playing the background music has no need to interact with the user, and hence it can be run as a service. Services are also ideal for situations in which there is no need to present a UI to the user. A good example of this scenario is an application that continually logs the geographical coordinates of the device. In this case, you can write a service to do that in the background. In this chapter, you will learn how to create your own services and use them to perform background tasks asynchronously.


The best way to understand how a service works is by creating one. The following Try It Out shows you the steps to create a simple service. Subsequent sections add more functionality to this service. For now, you will learn how to start and stop a service.

TRY IT OUT: Creating a Simple Service

codefile available for download at

1. Using Eclipse, create a new Android project and name it Services.

2. Add a new Java Class file to the ...

Get Beginning Android™ 4 Application Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.