A service in Android is a special component that runs in the background to perform long-running tasks. With the services, the application remains active in the background so that users can access multiple applications at the same time. This article describes how to implement an Android service, its life cycle, and more.
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 smartphone 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 their 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 would like to Enrich your career with an Android certified professional, then visit Mindmajix - A Global online training platform: “Android Training Course” Course. This course will help you to achieve excellence in this domain.
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 time, 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 a resource-intensive task, you must use asynchronous processing in the service.
There are mainly three types of services:
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.
[ Related Article: Introduction to Android ]
A service is defined as bound when the component of an application binds 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.
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.
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 specifies 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);
You have to declare all services in the manifestation file of your application. Here is the source code for declaring your service:
Add a <service> element as a child of the <application> element. Example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
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:
It starts the service bypassing the intent data to onStartCommand when it gets terminated.
It restarts the services only when the runtime has pending startService() call since the service termination.
There are two classes that a client can extend to start a service- Service, and IntentService.
Service is the base class of all the services. 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 that 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 that 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()
}
}
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.
[ Related Article: Android Toast Notifications ]
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.
In most scenarios, the activity and service have no requirement for direct communication. The service directly receives the intent data from the 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.
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.
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 a fast communication layer with the service.
To communicate with a service that runs in a different process, you can use IPL. Inter-process communication will use the AIDL file which you will create to communicate the data. It is similar to the Java interface, but allows communication only to files with AIDL extension .aidl.
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().
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.
[ Related Article: Android vs IOS - What is the Difference ]
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() {
}
}
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.
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 response or result.
Abound 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.
Abound service is terminated by Android, once the last client unbound. But the started service requires no clients and runs indefinitely.
When you destroy the calling component, it also destroys the bound services. But the started service keeps running even when the calling component is no more.
To start a bound service, you need to call out the command bindService(). While for the started service, the command is startService().
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 services as per requirements. We hope that the article provides you insight into Android services and their types. Feel free to connect with us in the comments section below for any queries.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Android Training | Nov 19 to Dec 04 | View Details |
Android Training | Nov 23 to Dec 08 | View Details |
Android Training | Nov 26 to Dec 11 | View Details |
Android Training | Nov 30 to Dec 15 | View Details |
I am Ruchitha, working as a content writer for MindMajix technologies. My writings focus on the latest technical software, tutorials, and innovations. I am also into research about AI and Neuromarketing. I am a media post-graduate from BCU – Birmingham, UK. Before, my writings focused on business articles on digital marketing and social media. You can connect with me on LinkedIn.