Chapter 8. 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. You as the developer 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. Essentially, whenever an activity needs your service, it will invoke it through an intent that starts the service. An already running service can receive the start message repeatedly and at unanticipated times. You can also stop a service, which is also called destroying it.

A service can be bound or unbound. Bound services can provide more specific APIs to other applications via an interface called AIDL (Android Interface Definition Language; see Chapter 14). For now, 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 for bound services are started and stopped ...

Get Learning Android 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.