Chapter 18. Started Services: At Your Service

There are some operations you want to keep on running, irrespective of which app has the focus. If you start downloading a file, for instance, you don’t want the download to stop when you switch to another app. In this chapter we’ll introduce you to started services, components that run operations in the background. You’ll see how to create a started service using the IntentService class, and find out how its lifecycle fits in with that of an activity. Along the way, you’ll discover how to log messages, and keep users informed using Android’s built-in notification service.

Services work in the background

An Android app is a collection of activities and other components. The bulk of your app’s code is there to interact with the user, but sometimes you need to do things in the background, such as download a large file, stream a piece of music, or listen for a message from the server.

These kinds of tasks aren’t what activities are designed to do. In simple cases, you can create a thread, but if you’re not careful your activity code will start to get complex and unreadable.

In addition to writing your own services, you can use Android’s built-in ones.

Built-in services include the notification service, location service, alarm service, and download service.

That’s why services were invented. A service is an application component like an activity ...

Get Head First Android Development, 2nd Edition now with O’Reilly online learning.

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