Working with the Service class in Android

in #utopian-io5 years ago (edited)

The service class in android represents one of the 4 primary components of android (the other 3 being Activity, Broadcast Receiver and Content Provider). This class represents a core component of the android framework and as such a concept every android developer must familiarize him/herself with.

What Will I Learn?

  • You will learn about the service class & its types
  • You will learn how to use the various types of services in your android application


  • Android Studio 2.3 and above
  • Basic Knowledge of native Android development using Java


  • Intermediate

Tutorial Contents

The service class is simply a normal java class under the android framework that is capable of running tasks in the background of an application and requires no user interface for interaction as all of its work happens behind the scenes.

Image Source

Services are particularly suited to performing tasks that take a long time to complete such as, streaming music/movie for a user or downloading a file over the internet. There are different types of services which include : Started services, Intent Services, Bound Services etc.

Started Services

Started services are launched by the other components of android such as activities and broadcast receivers. It runs indefinitely in the android background unless it is stopped via a call to the stopSelf() method or destroyed by the android runtime to free up resources.

Started services are launched by calling the startService() method of your activity or fragment and passing through as argument to the method the intent object which identifies the service to be started.
To add a started service to your android application,
Create a new class that extends the Service class, then override the onStartCommand() method which is responsible for handling a received intent and create a constructor that helps to pass in the service name as a string to the super class constructor

public class MyService extends Service{

public MyService(){

public void onCreate() {

public int onStartCommand (Intent intent, int flags, int startId){
//perform other operations
 return Service.START_STICKY;

The onStartCommand() method returns an integer that indicates to the android system how to control the destroyed service's restart options. START_STICKY indicates that the service should be restarted as soon as possible after it has been destroyed especially if the destruction occured after the method has returned.
Navigate to your AndroidManifest.xml file and add the following tag to the <application tag

android:name = ".MyService"
android:exported = "false"

The exported attribute helps android to know if you want your service to be available to other applications or not. Setting a value of false makes your service available for just your application.

protected void onCreate(Bundle savedInstanceState){
Intent intent = new Intent(this, MyService.class);

Intent Services

These type of services are similar to the started services, however they differ in the way they handle execution of tasks. By default the start services runs in the same thread as the component from which they are called, the intent service however avoids this by creating a new background thread for task execution and handles each request in an asynchronous manner.

Also, as soon as all the queued requests are executed by the intent service, it simply exits. The process of using the intent service is similar to the started service, but the difference lies in the method called for handling intent objects, in this case the onHandleIntent() method is called.

public class MyService extends Service{

public MyService(){
public void onCreate() {
public void onHandleIntent (Intent intent){
//perform background operations

It is worthy to note that in all services, the first method to be called is the onCreate() method and it is useful for performing initialization operations.

Bound Services

Unlike the previous two, bound services allow interaction with the component that started it and also returns results to such components. This component also known as a client binds to a bound service via the bindService() method passing in three parameters.

When the last client unbinds from a bound service, its unbindService() method should be called so as to unbind it and free up resources for the android runtime. To implement a bound service, create a class that extends the service class and type in the following code,

public class MyBoundService extends Service{
private final MyBinder myBinder = new MyBinder ();
public void onCreate() {

//perform initialization operations here
    public IBinder onBind(Intent intent) { \
return this.myBinder; 

public class MyBinder extends Binder{
public MyBoundService getService(){
return MyBoundService.this;


As stated earlier, the bound service allows for client interaction. To create this interaction an instance of the service is needed in the client class when the service is called via the bindService method.

The inner class (click my previous tutorial to see how to use inner classes in android) called MyBinder has its instance returned to the calling activity. That instance is then used to call the getService() method which returns an instance of the service to be used for interaction.
To do this, in your activity, type in the following code

protected void onStart(){
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);

Then make your activity class to implement the Service Connection interface and override the two methods listed below,

public class MainActivity extends Activity implements ServiceConnection{

public void onServiceConnected(ComponentName name, IBinder binder){
MyBoundService.MyBinder binder = (MyBoundService.MyBinder) binder;
MyBoundService myBoundService = binder.getService();
//more code after connection of service for interaction

public void onServiceDisconnected(ComponentName name){
//code to clear up resources

As can be seen, in the onStart, the service is bound to the activity via the bindService() method using the intent, activity context and a flag that ensures the service is automatically created as long as the binding exists.

Once the service is connected and notified as connected in the serviceConnected() method, the Binder object is received and cast to the binder inner class that we earlier created. This Binder object is then used to call the getService() method which returns the instance of the service that will be used for interaction with the client.

The case of interaction is simple from there henceforth as helper methods are created in the bound service class which are called from the activity (client) using the instance of the service that was returned by the getService() method.

To demonstrate this, examine this simple case whereby an arraylist is sent from the client(activity) to the service. In the service class create a variable to store the arraylist and a setter helper method.

public class MyBoundService extends Service{
private ArrayList<String> arraylist;

public void setArrayList(ArrayList<String> arraylist){
this.arraylist = arraylist;

From the activity or client, the arraylist can be stored as long as the service is connected via a call to setArrayList() method using the returned instance of the service,

myBoundService.setArrayList(new ArrayList<String>());

In conclusion

The service class is a powerful component in android. Seeing its amazing benefit, it should be used when needed. It is worthy to note that there is a Job Service which helps in scheduling tasks.

Thanks for reading, i hope you learned something new and worthwhile.

Posted on - Rewarding Open Source Contributors


Thank you for the contribution. It has been approved.

You can contact us on Discord.

Hey @davidemi I am @utopian-io. I have just upvoted you!


  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!


  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!


Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord

Wow, that's great to read the post. Actually, I love to read interesting stuff like this always and it gives me so much joy. But I am looking for some online writing service help for my essay writing work. I was facing so many problems in finding the best writing help for my work. Then my friend suggests to me where I can read the reviews about the top online writing services and I found it very useful for my work. I think if you ever face any type of essay or assignment help then you should try this website.

Coin Marketplace

STEEM 0.20
TRX 0.06
JST 0.025
BTC 22820.91
ETH 1567.23
USDT 1.00
SBD 2.60