Android services are important components of the Android ecosystem. They enable work to be done in the background regardless of the user activity. In this chapter, you will learn when Android services are best suited to situations, and how to use them in your application. More specifically, we will pass through the following recipes:
Android services are some of the building blocks available in Android, and they allow tasks to be performed in the background. In addition, they follow their own lifecycle, completely disconnected from the application lifecycle seen in Chapter 2, Mastering the Life and Death of Android Apps. There are three kinds of Android services that fulfill two specific uses:
The lifecycle of Android services is a lot simpler than that of standard applications, as depicted in the following figure. In this figure, the blue methods are shared by two kinds of services, whereas the green one is related to the started services. The red ones are related to bind services. These methods are callback methods that are invoked as the service is starting up:
Similar to applications, the services have the OnCreate()
and OnDestroy()
method states, which will make sure that the service is properly created and destroyed, respectively. For the started services, the OnStartCommand()
method is called right after the OnCreate()
method. The OnStartCommand()
method is the place to start background tasks. Also, this method returns a StartCommandResult
object that describes how the service should be restarted in case the Android operating system shuts it down in the extreme need for memory. For the bound services, clients can bind themselves to an already-running service that will trigger the OnBind()
method of the service. In the same way, when the clients unbind, they trigger the Unbind()
method. Both the services can be destroyed by calling a StopService()
or StopSelf()
method.
18.190.159.10