Android Development (45 Blogs) Become a Certified Professional

Android Tutorials for Beginners Part-3: Android Services

Last updated on Feb 24,2022 13.6K Views


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:

<service

android:name=“.MyService”

  android:enabled=“true” >

</service>

Code : MainActivity.java

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button play, stop;

play = (Button) findViewById(R.id.button1);

stop = (Button) findViewById(R.id.button2);

play.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

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

startService(service);

}

});

stop.setOnClickListener(new View.OnClickListener() {

@Override

  public void onClick(View v) {

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

stopService(name);

}

});

}

}

Code: MyService.java

public class MyService extends Service {

MediaPlayer mp;

@Override

public IBinder onBind(Intent arg0) {

return null;

}

@Override

  public void onCreate() {

  super.onCreate();

mp = MediaPlayer.create(getApplicationContext(), R.raw.song);

}

@Override

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

mp.start();

return 0;

}

@Override

public void onDestroy() {

mp.release();

super.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!

[dl url=”https://www.edureka.co/android-development-certification-course/?”  title=”Take FREE Webinar” desc=”” type=”” align=”” for=”webinar”]

Happy Learning!

You may also like these related posts:

Comments
27 Comments
  • Grey is a Lie says:

    Hi, The link for Android Tutorials for Beginners Part-4: Content Provider under “Related Posts” in this article is wrong. Please update.

    Great article on Services.

  • please post about shared preferences

  • Saravana Pandian says:

    This code is not working… because the intent part is not intent from the calss MainActivity to the MyService class…(i put taost in the MyService class to check whether it is working or not. but, after click the play button its keep idle state without playing clip song.) can u explain me why?

  • Lorri says:

    I constantly spent my half an hour to read this weblog’s posts all the time along
    with a mug of coffee.

  • Jams says:

    Very nice tutorial on Android Service. Easy to understand. Very well explained by taking very basic example so that a beginner can understand it easy. Thanks.

  • Darnie says:

    Very Nice Example…

  • josh says:

    good one.

  • Gafas Oakley says:

    Hi there, I enjoy reading all of your article post.
    I like to write a little comment to support you.

  • ricejoldell says:

    There is noticeably a bundle to understand about this. I assume you made certain nice points in capabilities also.

  • TydayAlloro says:

    I discovered your weblog site on google and check several of your early posts. Continue to keep up the especially wonderful operate. I just further up your RSS feed to my MSN News Reader. Looking for forward to reading even more from you later on!

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Android Tutorials for Beginners Part-3: Android Services

edureka.co