Android - Services Example


Services in android is one of the main component. Like Activity it has its own life-cycle.

Why to use a Service

Service is an application component which can be used to perform a long running task in the background. Unlike Activity they do not have any user interface associated with them. Service can continue to work in the background even if the user switches from our application.
service-android

A Service is an application component and it is created using java. For example : MyService.java

Now for a service to work we need to declare it in the android manifest file. For example : if we want to create a a service named MyService then we need to declare it inside manifest in the following way.

 <service android:name=".MyService"/>

Now to create a service you need to create a subclass of Service class.
 

package com.example.activitykb4dev;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        return super.onStartCommand(intent, flags, startId);
    }

}



Services can be of two types.

  1. Started Service.
  2. Bound Service.

 

In this note we will learn about Started Service.

Started service is started by calling startService() method from any application component. Started Service continues to run in the background until assigned task is finished. It continues to perform operation even when the component which has started the service gets destroyed.

onStartCommand() method of Service class is called whenever service gets started by another component like Activity. Service can be started with the help of intent.


Service in android runs in main thread

Service runs in the main thread i.e in the same thread where all activities run. If you want to perform some heavy task then you need to create a separate thread. Doing heavy operations such as "networking" blocks our main thread so idea is to use another thread for heavy operations.

We can use service to play media in the background, download a file, upload a file, networking operation and in the situation where we do not need user interface we can create a service to perform any task.

So this was a simple introduction about services in android.