Monday, July 18, 2016

Android Services - Introduction & Lifecycle

Android Services is a very useful component provided by Android, which runs in background and does not have any visual UI, as Activity have. Services are mostly used to perform the processing parts of Android Application.

An Android Service can be started by other Android component such as Activity or other service also.

We have already discussed in Android Application Components that Service in Android is implemented as a subclass of Service class.

A typical example of Android Service is listening to music while surfing on internet, here Music Player Application started an Android Service which runs in background and play music and you may also have noticed that in some music player that music keeps on playing even after you have closed the music player.

Android Services have two states
Started: In this case service is started by Application Component by calling startService()
Bound: In this Application Component binds to service by calling bindService()

Lifecycle of Android Services

Just like Activity, Services also have a similar lifecycle which tells how Android Services works such as startService(), onCreate(), onStartCommand(), onDestroy() etc.
Flowchart is show below to show the order how these methods are called.

Some of Callback methods of Android Services

These callback methods may be used to know the state of Android Service and to perform action at appropriate stage.
So lets start with some of Callback methods on Android Services.

1. onStartCommand()
Called when other Android Application Component requests the service to start using startService() method.

2. onCreate()
Called when Android Services is started

3. onBind()
This method is called when we another Android Application Component wants to bind with service.

4. onUnbind()
Called when component is disconnected from the service.

5. onDestroy()
Called when service is no longer used.

Note: It is your responsibility to stop the service when its work is done, by calling stopService() or stopSelf() method.

Now again take the example of Music player, when we start the music then onStartCommand() is executed and if have to join some component to this Android Service such to add a song to favorite then we have to bind other component to our service and then onBind() method is called.

Thanks for reading and be updated to this blog for new updates.


  1. Thanks Vishal, for this post
    Can you please also post an tutorial to show how to use services in android app.

    1. Thanks Shiva for your comment.
      I will try to add a post as per your request.

  2. But developing custom apps requires acquaintance with market trends, sound technical knowledge and an experts' hand. And a professional Android App Developer best fit your needs.