Android services

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
If you are intrested to learn about android technology Please visit Android Training Online




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 soon
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,To get more information about services please visit  Android training
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().

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.

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.


Comments

Popular posts from this blog

Android Interview Questions And Answers

Ten Things a Junior DBA Should Learn

SQL Server Interview Questions & Answers