Android Tutorials for Beginners Part-3: Android Services

Last updated on Feb 24,2022 13.8K Views

Android Tutorials for Beginners Part-3: Android Services

edureka.co

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. 

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:

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.

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/?utm_source=blog&utm_medium=banner&utm_campaign=freeclass”  title=”Take FREE Webinar” desc=”” type=”” align=”” for=”webinar”]

Happy Learning!

You may also like these related posts:

BROWSE COURSES