A service is an Android component that runs in the background without any user interaction. It can be started and stopped by any component.While it is running, any component can bind to it. A service can also stop itself. Some illustrative scenarios are

■ An activity provides the user a way to select a set of music files, which then starts a service to play back the files. During playback, a new activity starts and binds to the existing service to allow the user to change songs or stop playback.

■ An activity starts a service to upload a set of pictures to a website. A new activity starts and binds to the existing service to determine which file is currently being uploaded and displays the picture to the screen.

■ A broadcast receiver receives a message that a picture was taken and launches a service to upload the new picture to a website. The broadcast receiver then goes inactive and is eventually killed to reclaim memory, but the service continues until the picture is uploaded. Then, the service stops itself.

The general lifecycle of a service is illustrated in Figure 3.2.







running I

ÎThe service is stopped^ ^ (no callback) j






Service is [

running I



Client interacts with the service onRebind()

Figure 3.2 Service Lifecycle from

An aside on the third scenario: Any background task within a component will be killed when the component is killed. Therefore, tasks that are meaningful to continue even after the component stops should be done by launching a service. This ensures the operating system is aware active work is still being done by the process.

All services extend the abstract class Service or one of its subclasses. Similar to an Activity, the entry point to each service is the onCreate() method. There is no concept of pausing a service, but it can be stopped, which calls the onDestroy() method.

Was this article helpful?

0 0
Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment