Chapter 13. Services: At Your Service

There are some operations you want to keep on running, irrespective of which app has the focus.
As an example, If you start playing a music file in a music app, you’d probably expect it to keep on playing when you switch to another app. In this chapter, you’ll see how to use services to deal with situations just like this. Along the way, you’ll see how to use some of Android’s built-in services. You’ll see how to to keep your users informed with the notification service, and how the location service can tell you where you’re located.
Services work behind the scenes
An Android app is a collection of activities and other components. The bulk of your code is there to interact with the user, but sometimes you need to do things in the background. You might want to 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.
That’s why services were invented. A service is an application component like an activity but without a user interface. They have a simpler lifecycle than an activity, and they come with a bunch of features that make it easy to write code that will run in the background while the user is doing something else.
There are ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access