Chapter 10. Services

Services are among the main building blocks in Android. Unlike an activity, a service doesn’t have a user interface; it is simply a piece of code that runs in the background of your application.

Services are used for processes that should run independently of activities, which may come and go. Our Yamba application, for example, needs to create a service to periodically connect to the cloud and check for new statuses from the user’s friends. This service will be always on and always running, regardless of whether the user ever starts the activity.

Just like an activity, a service has a well-defined life cycle. As the developer, you get to define what happens during transitions between states. Whereas an activity’s state is managed by the runtime’s ActivityManager, service state is controlled more by intents. First, you must create the service. Whenever an activity needs the service, the activity will invoke the service through an intent, as described in Intents. This is called starting the service. A running service can receive the start message repeatedly and at unanticipated times. You can also stop a service, which is called destroying it.

A service can be bound or unbound. Bound services can provide more specific APIs to other applications via an interface called the Android Interface Definition Language (AIDL). We’ll focus on unbound services, where the life cycle of a service is not tied to the life cycle of the activities that started them. The only states ...

Get Learning Android, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.