Android Services Example Tutorial

Android Services Example Tutorial

Android Services Example Tutorial

Android Services Example Tutorial is  a detail tutorial on android Services. A service is a component that runs in the background to carry out long-running actions without requiring interacting with the user. For instance, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

A service like other application objects runs in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (like MP3 playback) or blocking (like networking) operations, it ought to spawn its own thread to do that work.

A service runs in the major thread of its hosting process – the service does not produce its own thread and does not run in a different process except you indicate otherwise.

This entails that, if your service is going to do any CPU intensive work or blocking operations like MP3 playback or networking, you ought to produce a new thread within the service to do that work. By making use of a different thread, you will minimize the danger of Application Not Responding (ANR) errors and the application’s major thread can remain committed to user interaction with your activities.

A service can basically exist in two states as illustrated in the table below:

StartedA service is started when an application component, like an activity, starts it by calling startService(). Once started, a service can run in the background for an indefinite period, even if the component that started it is damaged.
BoundA service is bound when an application component connects to it by callingbindService(). A bound service provides a client-server interface that offers components to interact with the service, send requests, attain results, and even do so across processes with interprocess communication (IPC).

A service has lifecycle callback techniques that you can put into practice to monitor changes in the service’s state and you can carry out work at the suitable stage.

To create a service, you produce a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines different callback methods and the most significant are explained below.  You don’t require implementing all the callbacks techniques. Nevertheless, it’s significant that you comprehend each one and implement those that see to it that your app acts the way users expect.

onStartCommand()The android system calls this technique when another component, like an activity, asks that the service be begun, by calling startService(). If you put this technique in practice, you have to stop the service when its work is done, by calling stopSelf() or stopService() techniques.
onBind()The system calls this technique when another component wants to attach with the service by calling bindService(). If you make use of this technique, you ought to make available an interface that clients make use of to interact with the service, by returning anIBinder object. You ought to constantly implement this method, but if you don’t want to permit binding, then you ought to return null.
onUnbind()The android system calls this technique when all clients have disconnected from a specific interface published by the service.
onRebind()The android system calls this technique when fresh clients have linked to the service, after it had beforehand been informed that all had disconnected in its on Unbind(Intent).
onCreate()The android system calls this technique when the service is initially created using onStartCommand() or onBind(). This call is needed to carryout one-time setup.
onDestroy()The system calls this technique when the service is no longer used and is being smashed. Your service ought to carry out this to clean up any resources like threads, registered listeners, receivers, and so on.

The example below will show you simple steps to create your own Android Service. Follow the following steps to modify an already created Android application:

The following is the content of the modified main activity file src/com.example.helloworld/ The file can include every one of the basic lifecycle techniques. StartService() and stopService() techniques have been added to start and stop the service.

import android.os.Bundle;
import android.view.Menu;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

 public void onCreate(Bundle savedInstanceState) {
 public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(, menu);
   return true;
 // Method to start the service
 public void startService(View view) {
 startService(new Intent(getBaseContext(), MyService.class));
 // Method to stop the service
 public void stopService(View view) {
  stopService(new Intent(getBaseContext(), MyService.class));

Following is the content of src/com.example.helloworld/ This file can have implementation of one or more techniques connected with Service based on requirements. Currently, we are going to put into practice only two methods onStartCommand() and onDestroy():

import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast; 

public class MyService extends Service {
   public IBinder onBind(Intent arg0) { 
     return null;
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   public void onDestroy() {
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

Following will the modified content of AndroidManifest.xml file. Here we have added <service…/> tag to include our service:

<manifest xmlns:android=""
android:versionName="1.0" >

android:targetSdkVersion="15" />

android:theme="@style/AppTheme" >

android:label="@string/title_activity_main" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>

<service android:name=".MyService" />

Following will be the content of res/layout/activity_main.xml file to include two buttons:

<LinearLayout xmlns:android=""
android:orientation="vertical" >

<Button android:id="@+id/btnStartService"

<Button android:id="@+id/btnStopService"
android:onClick="stopService" />


Following will be the content of res/values/strings.xml to define two new constants:

<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="start_service">Start Service</string>
<string name="stop_service">Stop Service</string>

A service is merely a component that can run in the background even when the user is not communicating with your application. Therefore, you ought to create a service only if you actually require it.

If you require to carryout work outside your major thread, but only while the user is communicating with your application, then you ought to possibly create a fresh thread rather than a service. For instance, if you intend to play some music, but only while your activity is running, you may create a thread in onCreate (), start running it in onStart (), afterward stop it in onStop(). Also think about using AsyncTask or HandlerThread, rather than the traditional Thread class.

To create a service, you ought to create a subclass of Service (or one of its accessible subclasses). In your implementation, you require to override a few callback techniques that take care of major aspects of the service lifecycle and make available machinery for components to connect to the service, if suitable. The most significant callback techniques you ought to override are:


The system calls this method when a different component, like an activity, requests that the service be started, by calling startService(). Immediately this technique is executed, the service is started and can run in the background for the foreseeable future. If you implement this, it is your duty to stop the service when it has finish its work, by calling stopSelf() or stopService(). (If you only want to provide binding, you don’t need to implement this method.)


 The system calls this method when a different component wants to connect with the service like to carry out RPC, by calling bindService(). In your implementation of this technique, you ought  make available an interface that clients use to communicate with the service, by returning an IBinder. You ought to constantly use this technique, but if you don’t want to allow connection, then you should return null.


The system calls this method when the service is first created, to carry out one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this technique is not called.


The system calls this method when the service is no more in use and is being destroyed. Your service ought to implement this to clean up any resources like threads, registered listeners, receivers, etc. This is the last call the service receives.

Creating a Started Service

A started service is one that a different component starts by calling startService(), resulting in a call to the service’s onStartCommand() method.

When a service is started, it has a lifecycle that’s autonomous of the component that started it and the service can run in the background for an indefinite period, even if the component that started it is destroyed.  Owing to this, the service ought to stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService().

An application component like an activity can start the service by calling startService() and passing anIntent that spells out  the service and includes any data for the service to be make use of. The service receives this Intent in the onStartCommand() method.

For example, suppose an activity requires to save some data to an online database. The activity can start a companion service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet and carries out the database transaction. When the transaction is done, the service stops itself and it is smashed.

Note: A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service carries out intensive or blocking operations while the user communicates with an activity from the same application, the service will slow down activity performance. To stay away from impacting application performance, you ought to start a new thread inside the service.

Conventionally, there are two classes you can broaden to create a started service:


This is the base class for all services. When you extend this class, it’s significant that you create a new thread in which to do all the service’s work, because the service makes use of application’s main thread, by default, which can possibly slow the performance of any activity your application is running.


This is a subclass of Service that makes use of a worker thread to take care of all start requests, one at a time. This is the best alternative if you don’t require that your service take care of many requests concurrently. All you require is to put into practice onHandleIntent(), which accepts the intent for every start request so you can do the background work.

Extending the IntentService class

Due to the fact that majority of started services don’t need to handle multiple requests concurrently (which can in fact be an unsafe multi-threading situation), it’s almost certainly best if you implement your service using the IntentService class.

The IntentService performs the following:

  • Creates a default worker thread that carries out all intents delivered to onStartCommand() different from your application’s main thread.
  • Creates a work line up that passes one intent at a time to your onHandleIntent() implementation, to save you from every having to bother about multi-threading.
  • Exists the service after all start requests have been handled, in order that you never have to call stopSelf().
  • Makes available default implementation of onBind() that returns null.
  • Makes a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent()

All this adds up to the fact that all you require to do is implement onHandleIntent() to do the work supplied by the client. (Though, you also require to make available a small constructor for the service.)

 Starting a service

You can start a service from an activity or other application component by passing an Intent (specifying the service to start) to startService(). The Android system calls the service’s onStartCommand() method and passes it the Intent. (You ought to never call onStartCommand() straightforwardly.)

Creating a Bound Service

A bound service is a service that permits application components to bind to it by calling bindService() in order to create a long-standing connection (and commonly does not permit components to start it by calling startService()). You ought to create a bound service when you want to communicate with the service from activities and other components in your application or to expose a few of your application’s functionality to other applications, via interprocess communication (IPC).

To create a bound service, you ought to implement the onBind() callback technique to return an IBinder that defines the interface for communication with the service.

Add a Comment