Android Tutorials for Beginners Part-3: Android Services

Recommended by 56 users

Dec 5, 2012
Android Tutorials for Beginners Part-3: Android Services
Add to Bookmark Email this Post 8.6K    28

This post is the third in our series of Android Tutorials for beginners, and discusses the Service component of Android in some detail. In our previous Android tutorials we discussed Activities and Intent; if you missed them, read them here:

Android Tutorials for Beginners Part 1: Activities

Android Tutorials for Beginners Part 2: Intent

Android Tutorials for Beginners: Android Services

What are Services in Android System?

1) Faceless components: The components of Android system that run in the background are Service components. They are very much like activities, only without a User Interface.

2) Taking care of long running background tasks: They carry out long-running tasks desired by the application (without user intervention). Services run the background tasks that do not require a User Interface.

3) Unaffected by activity switching: Each Service has a specific job, and they keep at it if you switch between different Activities, or even if you switch to a different application altogether.

4) It can also provide functionality to other applications.

5) Example of Service: A good example is your music player.

When you play music in your Android handset using a playlist, the music player takes care of the job itself, without user intervention. You do not have to change the song every time one song ends. This automation is due to the service component of Android.

We have discussed the music player example in detail later in the post. Keep reading for it to make sense! :)

Watch this video to get an overview of Services.

Service Components in Facebook Application

Talking about Facebook application again, the various friend feeds and friendship notifications etc. are examples of Services. The new friend invites always update in the background, whether you interact with it or not. 

Android Tutorials for beginners: Android Services

Service Lifecycle

Let us now discuss the Service life-cycle. Because a Service lacks a user interface, it always runs in the background (unlike an activity). As a result, its life stages vary a bit from Activity’s life-cycle. You would remember that an activity is in a paused state when it is visible but the user is not interacting with it.

As a Service always runs in the background no matter which activity the user is interacting with, Paused State is not a possibility.

Therefore, a Service has the following stages:

  • Starting
  • Running
  • Destroyed

Android Tutorials for beginners: Android Services lifecycle

Forms of Service

A Service can have two forms:

1) Started/Unbound: In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.

2) Bound: An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.

An unbound activity runs indefinitely, whereas the lifespan of a bound activity depends on the application components that bind to it.

When are the Services running in the background destroyed?

Even though (by definition) services should carry out long running operations indefinitely, they are fated to be eventually killed by the Android system, if they run in the background.

This is how it happens:

1) When a Service starts, it runs in the main process:

A service when created does not create a separate thread/process for itself (unless instructed to do so); instead, it runs in the main thread of the running application, thus consuming the memory resources of the main system.

2) What happens in case of low system memory?

The system would choose to close the components that are low priority, but are still consuming the system resources. Thus, the background components not in user focus are the first ones the system kills. Therefore, it would destroy the services running in the background. This is to free system resources for more important components (Example: for the activity in the foreground interacting with the user).

3) Does system follow a pattern while killing services to free resources?

Yes it does! Read on to find out:

a) Unbound Service: Over time, the system pushes down a long-running service to lower priority in the list of background tasks, and this service is more likely to close first (if unbound), when memory shortage occurs.

b) Services bound to foreground activity: The services that are bound to an activity or any other application component running in the foreground are less likely to be killed than an unbound activity.

c) Foreground Services: The system would never kill a service if it were declared to run in the foreground. We would discuss more about this in later Android tutorials. Stay put!

4) How to keep a Service from being killed?

a) You can create separate threads while creating services for the services to run. Thus, there is reduced consumption of main application memory, and the likelihood of the service being destroyed due to memory shortage is lower than otherwise.

b) As discussed before, you can declare a Service to run in the foreground. This can prevent the system from killing the Service.

Android Tutorials: Services Example

As this is a beginners’ Android tutorial, we have used the most basic example of a Service, i.e. Music Player.

Here are the code and snapshots for playing and stopping a song using a Service:

Follow the steps described in this Android Tutorial:

Step 1: Create a new Android Project with the class name MainActivity.

Step 2: Add two buttons in layout and name them as play and stop.

Step 3: Set the onClick Listeners of both buttons inside the MainActivity.

Step 4: Create a new class “MyService” and extends it to Service Class

Step 5: Make a new folder named as “raw” inside the “res” directory, and copy a song inside it.

Android Tutorials for beginners: Services component of Android

Tag to add in Manifest:



  android:enabled=“true” >


Code :

public class MainActivity extends Activity {


protected void onCreate(Bundle savedInstanceState) {



Button play, stop;

play = (Button) findViewById(;

stop = (Button) findViewById(;

play.setOnClickListener(new View.OnClickListener() {


public void onClick(View v) {

Intent service = new Intent(MainActivity.this, MyService.class);




stop.setOnClickListener(new View.OnClickListener() {


  public void onClick(View v) {

Intent name = new Intent(MainActivity.this, MyService.class);







public class MyService extends Service {

MediaPlayer mp;


public IBinder onBind(Intent arg0) {

return null;



  public void onCreate() {


mp = MediaPlayer.create(getApplicationContext(),;



public int onStartCommand(Intent intent, int flags, int startId) {


return 0;



public void onDestroy() {





We will cover advanced topics of Services (for instance, How to create Service components (started and bound)) in subsequent Android tutorials. Stay tuned for that!

For now,  join this live Android tutorial!

Happy Learning!

You may also like these related posts:

Share on
  • khyati

    plz tl me fast…

  • AnujD

    Hello, thanks for this tutorial. Its easy to understand. I am working on a music player and I am using Bound Service and IPC. So is this approach correct for a music player? So far it is working fine, but I don’t know if my way is correct or not.

    I am binding service in MainActivity and then use that IBinder throughout my project to communicate with service.

    • EdurekaSupport

      Hi AnujD, using bound service is fine in Mediaplayer as it covers all
      the functions that are required to perform on this, like start(), stop() etc

      • AnujD

        Thank you for your response. Previously i was using AIDL Bound service, now I am not using AIDL-file as direct binding with MainActivity is enough to use methods in service.
        Now, the question is how do you connect/bind a single service with multiple activities?

        Example: I have 2 activities- MainActivity & MPlayerActivity. I bind service in MainActivity using a static connection object, and then use that object in all activities where i want to use service methods.
        Is this way correct? Or is there some other proper way?


        • EdurekaSupport

          Hi Anuj!! According to the example that you have given, with the help of Mainactivity you can pass the value to MPlayerActivity using intent or bundle method, it will help you to work with multiple activities simultaneously.

          • AnujD

            Yes it works. Now the only problem is that – System sometimes kills MainActivity. So binder object becomes null. Can we somehow prevent this auto kill of Activity by android system?

          • EdurekaSupport

            Anuj, if Program is already running then system kills the activity. If system memory is low this happens. Try to increase the system memory allocated to AVD and try again.

          • AnujD

            Yes, I konw that. But I am talking about real device.
            What’s happening is – A Few times my MainActivity gets killed by system. And as I said earlier I am passing and using Service Connection Obj in other activities. Now if I tried to access it, it gives null because MainActivity is killed.

  • khyati

    m getting error in mp = MediaPlayer.create(getApplicationContext(),;
    what to do..?

    • EdurekaSupport

      Hi Khyati, the code looks fine. The only issue can be that file should
      be placed in raw folder in the project.

      • khyati

        thnx yeh dat was only da mistake n i solved it..m done with it…

        • AnujD

          Okies :-) Happy Coding ;)

      • AnujD

        What error you are getting?

24 X 7 Customer Support X

  • us flag 1-800-275-9730 (Toll Free)
  • india flag +91 88808 62004