Easy Tutorial
❮ Android Overview Android Tutorial ❯

Android Service

A service is a component that runs in the background to perform long-running operations that do not require user interaction. It can continue working even if the application is destroyed. Services basically have two states:

State Description
Started An Android application component, such as an activity, starts the service by calling startService(), making it a Started service. Once started, it can run indefinitely in the background, even if the component that started it is destroyed.
Bound When an Android application component binds to the service by calling bindService(), the service is in the Bound state. A Bound service provides a client-server interface to allow components to interact with the service, such as sending requests, receiving results, and even performing inter-process communication (IPC).

Services have lifecycle methods that can be implemented to monitor changes in the service's state and perform work at the appropriate stages. The left diagram below shows the lifecycle when a service is created via startService(), and the right diagram shows the lifecycle when a service is created via bindService():

To create a service, you need to create a Java class that extends the Service base class or one of its well-known subclasses. The Service class defines various callback methods and most important methods. You do not need to implement all the callback methods. However, it is important to understand all the methods. Implementing these callbacks ensures that your application behaves the way users expect.

Callback Description
onStartCommand() This method is called by the system when another component (such as an activity) requests the service to be started by calling startService(). If you implement this method, you are responsible for stopping the service when the work is done by calling stopSelf() or stopService().
onBind() This method is called when another component wants to bind to the service by calling bindService(). If you implement this method, you must return an IBinder object to provide an interface for the client to communicate with the service. You must implement this method; if you do not want to allow binding, return null.
onUnbind() This method is called when all clients have disconnected from a particular interface published by the service.
onRebind() This method is called when a new client connects to the service, after it had previously been notified that all had disconnected via onUnbind(Intent).
onCreate() This method is called when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time setup.
onDestroy() This method is called when the service is no longer useful and is being destroyed. Your service should implement this method to clean up any resources such as threads, registered listeners, or receivers.

The following main service demonstrates the lifecycle of each method:

package com.tutorialpro.androidservices;

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

public class HelloService extends Service {

    /** Indicates the mode in which the service is to run after being 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() {

    }

    /** Called when the service is started via startService() */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return mStartMode;
    }

    /** Called when clients bind to the service via bindService() */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

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

    /** Called when a client binds to the service after onUnbind() has been called */
    @Override
    public void onRebind(Intent intent) {

    }

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

    }
}

Example

This example will walk you through the simple steps to create your own Android service. Follow the steps below to modify the Android application created in the Hello World example chapter:

Step Description
1 Create an Android application using Android Studio IDE and name it androidservices under the package com.tutorialpro.androidservices. Similar to the Hello World example chapter.
2 Modify the main activity file MainActivity.java to add startService() and stopService() methods.
3 Create a new Java file MyService.java under the package com.tutorialpro.androidservices. This file will implement the Android service-related methods.
4 Define the service in the AndroidManifest.xml file using the <service.../> tag. An application can have one or more services without any restrictions.
5 Modify the default layout in the res/layout/activity_main.xml file to include two buttons within a linear layout.
6 Do not make any changes to the constants in the res/values/strings.xml file. Android Studio will handle the string values.
7 Start the Android emulator to run the application and verify the results of the changes made.

Below is the modified content of the main activity file src/com.tutorialpro.androidservices/MainActivity.java. This file includes all basic lifecycle methods. We added startService() and stopService() methods to start and stop the service.

package com.tutorialpro.androidservices;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, 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));
    }
}

The following is the content of src/com.tutorialpro.androidservices/MyService.java. This file can implement one or more methods associated with the service based on requirements. For beginners, we only implement onStartCommand() and onDestroy():

package com.tutorialpro.androidservices;

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

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    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;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

The following modification is made to the AndroidManifest.xml file. Here, the <service.../> tag is added to include our service:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialpro.androidservices"
    android:versionCode="1"
    android:versionName="1.0">

    &lt;uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="22" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        &lt;activity
            android:name=".MainActivity"
<activity 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" />

</application>

</manifest>

The following is the content of the res/layout/activity_main.xml file, which includes two buttons:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Service Example"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="www.tutorialpro.org"
        android:textColor="#ff87ff09"
        android:textSize="30dp"
        android:layout_above="@+id/imageButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:src="@drawable/ic_launcher"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="Start Service"
        android:onClick="startService"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:id="@+id/button"
        android:onClick="stopService"
        android:layout_below="@+id/button2"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignStart="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_alignEnd="@+id/button2" />

</RelativeLayout>

The following is the content of the res/values/strings.xml file, which defines two new constants:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Android Services</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="menu_settings">Settings</string>
    <string name="action_settings">Settings</string>

</resources>

Let's run the newly modified My Application app. I assume you have already created an AVD while setting up the environment. Open your activity file from your project, and click on the toolbar to run the app.

Now click the "Start Service" button to start the service, which will execute the onStartCommand() method we wrote. A message "Service has started" appears at the bottom of the emulator, as shown below:

Click the "Stop Service" button at the bottom to stop the service.

❮ Android Overview Android Tutorial ❯