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
-
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.
-
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
- onStartCommand()
- onBind()
- onCreate()
- 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 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); // If we get killed, after returning from here, restart return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed",Toast.LENGTH_LONG).show(); } } |
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.
1 2 |
<service android:name=".MyService" android:exported="false" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="pk.edu.riu.ecms4031.servicedemo.MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyService" android:exported="false" /> </application> |
Add Buttons to Start and Stop the Service in Layout File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/heading" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/start" android:onClick="startService" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" android:onClick="stopService" /> |
Specify Button and Label Text in Strings.xml
1 2 3 4 5 6 |
<resources> <string name="app_name">MyServiceApp</string> <string name="heading">Demonstrating Started Service</string> <string name="start">Start Service</string> <string name="stop">Stop Service</string> </resources> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Method to start the service public void startService(View view) { Intent intent = new Intent(this, MyService.class); <span style="color: #800080;">startService(intent);</span> } // Method to stop the service public void stopService(View view) { Intent intent = new Intent(this, MyService.class); <span style="color: #800080;">stopService(intent);</span> } } |

Run Service in Background
Add START_STICKY as a return type of onStartCommand() method in MyService.java file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); // If we get killed, after returning from here, restart return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed",Toast.LENGTH_LONG).show(); } } |
Perform any Task Through the Service
I used runnable thread to keep displaying the toast in the service as a background task.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); // Normally we would do some work here. for (int i = 0; i < 5; i++) { new Handler().postDelayed(new Runnable(){ @Override public void run() { } }, 5000); Toast.makeText(this, "Loop: "+i, Toast.LENGTH_LONG).show(); } stopSelf(startId); //auto destroy after task completion // If we get killed, after returning from here, restart return START_STICKY; } |

Download Source Code of Android Service Android Studio Project
Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!