Android Service – Types and lifecycle | Bound and Unbound Service

Android Service is a component which doesn’t have any UI and it runs in the background.

It can update UI elements (UI elements of the application which is currently using the service).

Services allow sharing functionality among applications without creating a physical copy of the class.

There are two types of Android Service

Bound Android Service

The Android service which works for specific activity or application is called bound services.

Unbound Android Service

The Android service which is continuously running or system provided services are called unbound services.

The methods in the lifecycle of Bound and Unbound Services are as follows:

Bound Services

  1. onCreate()
  2. onBind()
  3. onUnbind()
  4. onDestroy()

Unbound Services

  1. onCreate()
  2. onStartCommand()
  3. onDestroy()

 

The figure below explains the lifecycle of Bound and Unbound Android Service.

Android Service

Let’s know about these methods and how they are utilized in android development.

onStartCommand()

The system calls this method when another component, such as an activity, requests that the service is started, by calling startService().

Once this method executes, the service is started and can run in the background indefinitely.

If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService().

onBind()

The system calls this method when another component wants to bind with the service by calling bindService().

onUnbind()

The system calls this method when all the clients are disconnected from a particular interface that is given by the service.

onCreate()

The system calls this method when the service is created the first time, It uses onStartCommand() or onBind().

onDestroy()

The system calls this method when the service is no longer used and is being destroyed. This is the last call the service receives.

Declare the service in AndroidManifest.XML file 

Create Android Service in Application

It is very simple to create our own service, in the following code we will see how to create the service class with its methods.

 

Team RCV Academy

About Team RCV Academy

RCV Academy Team is a group of professionals working in various industries and contributing to tutorials on the website and other channels.

View all posts by Team RCV Academy