Blog

Android Services

  • (4.0)
  • | 1150 Ratings

Introduction


Android, developed by Google, is one of the best-operating systems for mobiles and digital cameras. It was under Android.Inc before Google took over it in 2005. Since then, many smartphones companies are using this OS for their mobile and tabs.


The 2017 data from shows that 86% of smartphones put up for sale used Android as their OS. By 2018, this increased to 88% strengthening the hold of this operating system on the market. (Source-Statista)


The above data calls for developers starting out to learn every minute detail about Android. This OS has various features, components, and tools which help develop unique applications for smartphones.


Most Android apps require background execution for various functions. For that, if you create a thread or an executor in the app’s activity, it will have unstable results. It is because a simple screen orientation disrupts things. You can handle this with various tools and the best one is Services.


Android Services is a component that doesn’t have a user interface, but it performs long-running operations in the background. For instance, if the user is listening to music and wants to check his email without turning the music off, he can. The user can switch to the other apps, and the music will continue to run in the background because of the service component of Android.


In this blog, we will learn in detail about Android Services and its types, feature, lifecycle, implantation process and so on. In short, after reading this article, you will know how to create and consume services.


What is a Service?


A service is an Android component that runs in the background according to the requirement of the user. While running in the background, it has no direct contact with the user. Services keep the app up and running in the background for long even when the user is not using it. For instance, listening to music or handling network operations.


Even if you close the application; the services keep running and perform a repetitive and long operation. These operations include downloads, checking and upgrading to new data and so on.


They have no user-interface which allows users to switch from app to app, while they run behind the curtains. Most of the times, Android doesn’t terminate these services, but if they do, you can re-configure and re-start them after the system has enough system resources available.


A service by default runs in the same process as that of the main application thread. If you want to run it in the background to perform resource intensive task, you must use asynchronous processing in the service.


There are mainly three types of services:


Started


A service is defined as started when the component of an application starts it by giving the command startService(). You can stop this service by giving the command stopService(). It can also stop running by calling itself stopSelf().


Once you start this service, it will run in the background indefinitely, even if the initial component that started it is no more. In Android, the started service performs a single operation without returning any result to the caller.


Bound


A service is defined as bound when the component of an applications bind it by giving the command bindService(). 

It offers a client-service interface allowing the component to interact with the service. It also lets it send requests, get results and also perform across processes with inter-process communication (IPC).

To unbind the service, give the command unbindService(). In Android, you can bind multiple components, but in case one gets destroyed, all other components will face the same fate.


Foreground


These are the main types of services, but there is one more type of service called foreground. It performs operations that the user can notice. It is an absolute must for them to display a notification. Like the other two, it continues to run in the background even when the user is not using the app.


How to implement a service?


How to create a start Service?


In Android, you need a subclass of a Service for creating a service. You can either create the subclass or use the existing one. The application component like activity passes an intent which specify the service to start by calling- startService(). It results in calling the service’s onStartCommand() method.

Sample code for starting a service: 

Intent intent = new Intent(this, MyService.class);
startService(intent);

How to declare a Service in Manifest File?


You have to declare all services in the manifestation file of your application. Here is the source code for declaring your service:


Add a element as a child of the element. Example:


<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

Service Restart Behavior

The service returns an int, in its onStartCommand()method call. It defines its restart behavior which is used in the case of Android terminating the service. Here are the common methods for doing this:


Service.START_STICKY

It starts the service bypassing the intent data to onStartCommand when it gets terminated. 


Service.START_NOT_STICKY

It restarts the services only when the runtime has pending startService() call since the service termination.


Android IntentService


There are two classes which a client can extend to start a service- Service and IntentService.


Service is the base class of all the service. It uses the main thread of your application slowing down the performance of the activity that the application is running.


Android IntentService


It is the subclass of Service. It uses a worker thread which handles all of the start requests one by one. To implement this, use onhandleIntent(). It will receive the intent for every start service, and your background work will complete.


It Creates a work queue which allows only one intent to pass at a time to onHandleIntent() implementation. It declines the chances of multi-threading.


It stops the service without you having to give the command stopSelf().


Here's the data source for implementing IntentService:


/**
 * A constructor is required, and must call the super [android.app.IntentService.IntentService]
 * constructor with a name for the worker thread.
 */
classHelloIntentService:IntentService("HelloIntentService"){
    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    overridefun onHandleIntent(intent:Intent?){
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try{
            Thread.sleep(5000)
        } catch (e:InterruptedException){
            // Restore interrupt status.
            Thread.currentThread().interrupt()
        }
    }

How to implement a bound service?


To start the bound service, you have to call bindService(). You can implement the bound service when you need to interact with the service.


For a bound service, you need to use onBind() callback method to implement it. It will return an IBinder that will define the interface for communicating with the service.


For this service, you have to define the interface specifying the communication process between a client and service.


The bound service supports multiple clients simultaneously. Once your interaction with the service is complete, call unbindService() to unbind. The system destroys the service, when there are no clients to bind.


How to communicate with a service?


There are several options available for an activity to communicate with a service. Below we will discuss these options and will also let you know which one to use.


1. By Using Intent data


In most scenarios, the activity and service have no requirement for direct communication. The service directly receives the intent data from Android component's starting point. After that, it is easily able to perform its work.


It works best for local and services that run their own process.


2.  By using receiver


You can make use of broadcasts and registered receivers for communicating with a service. In this scenario, the services need to give a signal to the activity/application letting them know that their processing is complete.


3. Application binding to local service


If you start the service and activity in the same process, they are directly bound to each other. It is a simple and efficient way of communication. We recommend this highly for activities that require fast communication layer with the service.


4. AIDL 


To communicate with a service that runs in a different process, you can use IPL. Inter-process communication will use AIDL file which you will create to communicate the data. It is similar to Java interface, but allows communication only files with AIDL extension .aidl.


Android Service Life Cycle


An Android service has a life cycle; it is known as lifecycle callback methods. The developer can implement this lifecycle callback method to keep a watch on any changes that the service state goes through. Monitoring this will aid you to perform work on this at the appropriate stage and time. 

The image below illustrates the lifecycle of an Android service. It shows both the method of creating a service. Through startService() and bindService().


Android Service CallBack methods


To create a service, you can either create a subclass or use an existing one. While implementing these callbacks, you need to override some callback methods. These callback methods handle key aspects of the lifecycle of a service. Below is the list of crucial callback methods that you can override or implement as per your requirement. In any case, you should know and understand them deeply.


Here are the most important callback methods:


  • onStartCommand(): The system uses this callback method when another component like an activity makes a request for the service to be started. It gives the command startService() for  this and when you implement this service, you are responsible for stop it by calling stopSelf().
    • Once started, it will run in the background indefinitely.
  • onBind(): When some other components wants to bind with the service, the system callback this method by giving the command bindService ().
    • When you use this method, you have to provide an interface for clients to communicate with the service, by returning an IBinder object. 
  • onUnbind(): When all clients disconnect from a specific interface published on the service, the system calls for this method.
  • onRebind(): Once the system receives the notice that clients have disconnected, it callback this method for connecting with new clients.
  • onCreate(): The system invokes this method when the service is initially created using onStartCommand() or onBind(). 
  • onDestroy(): The system invokes this method when the clients/Android destroys the service.  method Your need to implement this callback so that the service clean up any resources, threads, listeners and so on.

Here is how you can create a service with all callbacks:


package com.tutorialspoint;

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

public class HelloService extends Service {

/** indicates how to behave if the service is killed */
int mStartMode;

/** interface for clients that bind */
IBinder mBinder;

/** indicates whether onRebind should be used */
boolean mAllowRebind;

/** Called when the service is being created. */
@Override
public void onCreate() {

}

/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}

/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}

/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {

}

/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {

}
}

Android Life Cycle Start Service VS Bound Service


Now, that we know what start and bound services are, and how you can implement them, let’s check out the major differences between them.


Start Service VS Bound Service -Communication


In a bound service, you have the option to communicate with the activity and vice-versa. That is, it allows two-way communication between them. But, in a started service, there is no guarantee that the client activity will get any respond or result.


Start Service VS Bound Service- Serving clients


A bound service serves multiple clients (you require one bound client for this) whereas a started service performs a single operation and once it completes the service, it shuts down.


 Start Service VS Bound Service- Termination


A bound service is terminated by Android, once the last client unbound. But the started service requires no clients and runs indefinitely.


 Start Service VS Bound Service- calling component destruction


When you destroy the calling component, it also destroys the bound services. But started service keeps running even when the calling component is no more.


Start Service VS Bound Service: Implementation


To start a bound service, you need to call out the command bindService(). While for the started service, the command is startService().


Start Service VS Bound Service- Use


You can use the bound service for long-standing operations and connections. You use the started service for completing a task.


Conclusion


A developer can create, begin, or stop a service as per requirements. We hope that the article provides you insight about Android services and its types. Feel free to connect with us in the comments section below for any queries. 


Explore Android Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close