Services in Android

In the previous tutorial, you have learned about Google Maps Android API. In this tutorial, you will learn about Services in Android, difference between thread and service along with the components and use of Android Services.

Introduction

A service is a component of any application that runs in the background to perform long-running tasks and when you don’t need to involve the user interaction with the application and user can keep on doing other tasks. A service does not provide a user interface. For example, playing music in the background while the user is using some different application or when fetching data over the network.

Service VS Thread

You might think about threads if you consider service as a parallel task. You should use a service if you need a component that can run in the background even when the user is not interacting with your application. And you must create a thread if you want to perform any task outside your main thread but the thread can only be used when the user is interacting with your application.

Service

Forms of Services in Android

A service can essentially be in two forms. i.e.

  • Started
  • Bound
  1. Started Services in Android

    A service is started when an application component like an Activity, starts it by calling its startService() method. Once a service is started, it can run in the background indefinitely, even if the component that started the service is destroyed. Usually, a started service can perform a single operation and does not return any result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should automatically stop itself.

  2. Bound Services in Android

    A service is bound when an application component binds to it by calling its bindService() method. A bound service offers the client-server interface that allows the components to interact with the service i.e. send requests to the service, get results from the service, etc. A bound service is dependent on the component; it is bound to. It only runs only as long as another application component is bound to it. You can bind multiple components to a service at once, but when all of the components are unbound the service will be automatically destroyed.

Started and Bound Services in Android

A service can run both ways; It can be started and bound at the same time. It is simply a matter of whether you implement a couple of call back methods i.e.

onStartCommand() allow components to start it.

onBind() to allow binding.

Using Services in Android

Any application (even any other application) can use the service, regardless of whether your application is started, bound or both. Similar to the activities, by using intents. You can also make your service, private(in Manifest file). Making a private service will block access from other applications.

Running a Service

A service runs in the main thread of its hosting process; the service does not create its thread. A service can also not run in a separate process; you need to specify if you want to run the service in a separate process. This means that if your service is going to perform any CPU oriented intensive work or blocking task (such as mp3 playback or networking). You should create a new thread inside the service to perform such task. By using separate thread inside your service, you can reduce the risk of ANR (Application Not Responding) errors. So the main thread will keep on performing UI interactions and stay dedicated to user interaction with the application.

Creating Services in Android

To create a service, you must create a subclass of Service or one of its existing subclasses. Override and implement some of the callback methods. Most important callback methods are

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

onStartCommand()

The Android system calls this method when another component requests the service to be started, by calling startService() method. Once this method executes, the service is started and can then run in the background. If you implement this method, you should also destroy it when the task is performed, by calling stopSelf() or stopService() methods.

If you only want to provide the binding, you are not required to implement this method.

onBind()

The Android system calls this method when another component wants to bind with the service by using bindService() method. In the implementation of this method, you must provide an interface through which other components or clients can communicate with the service, by returning an IBinder.

Implementation of this method is compulsory, but if you don’t want to allow binding, you should return null then.

onCreate()

The Android system calls this method when the service is first created, to perform one-time setup procedures before onStartCommand() or onBind() is called. This method is not called if the service is already running.

onDestroy()

The Android System calls this method when there is no need of the service or the service is not in use and being destroyed. Your service should implement this method to clean up any resources such as threads, receivers, registered listeners, etc. This is the last message received by any Android service.

Android Services Lifecycle

Android Services Life Cycle
Android Services Life Cycle

Android Services Demo

Download Source Code of Android Service Android Studio Project

To create first Android service, you must

  • Create a service class.
  • Define your service in AndroidManifest.xml file.
  • Modify the activity.

Create Service Class

Create a service by extending your new Service class from Service class, override onBind(), onStartCommand() and onDestroy() methods.

Define Service in Android Manifest

Define your service in AndroidManifest.xml by using <service  /> tag inside <application> tag before the closing tag </appliation>. Read more about service element.

Add Buttons to Start and Stop the Service in Layout File

Specify Button and Label Text in Strings.xml

Implement Button Click Methods to Start and Stop the Service

In the main Activity of your Service application, implement startService(View v) and stopService(View v) methods to start and stop the service.

Start and Stop Android Service Demo
Start and Stop Android Service Demo

Run Service in Background

Add START_STICKY as a return type of onStartCommand() method in MyService.java file.

Perform any Task Through the Service

I used runnable thread to keep displaying the toast in the service as a background task.

Android Background Service
Android Background Service

Download Source Code of Android Service Android Studio Project

Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!

Leave a Reply

Your email address will not be published. Required fields are marked *