Home » Android » Android Framework » Understanding Android Services with Example

Understanding Android Services with Example

A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface.

There are Three different types of services –

  1. Foreground – A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a status bar icon. Foreground services continue running even when the user isn’t interacting with the app.
  2. Background – A background service performs an operation that isn’t directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.
  3. Bound – A service is bound when an application component binds to it by calling bindService().

Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application) in the same way that any component can use an activity—by starting it with an Intent. However, you can declare the service as private in the manifest file and block access from other applications.

The service Basics

To create a service, you must create a subclass of Service or use one of its existing subclasses.

Important callback methods

  1. onStartCommand()
    The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.
    Another Application -> startService -> onStartCommand() in service.
  2. onBind()
    The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). You must always implement this method; however, if you don’t want to allow binding, you should return null.
    @Override
    public IBinder onBind(Intent arg0) {
    return null;
    }
  3. onCreate()
    The system invokes this method to perform one-time setup procedures when the service is initially created.
  4. onDestroy()
    The system invokes this method when the service is no longer used and is being destroyed.

If a component starts the service by calling startService() (which results in a call to onStartCommand()), the service continues to run until it stops itself with stopSelf() or another component stops it by calling stopService().

Declaring a service in the manifest

You must declare all services in your application’s manifest file, just as you do for activities and other components. To declare your service, add a < service > element as a child of the < application > element. Here is an example:

<manifest ... >
  ...
  <application ... >
      <service android:name="com.android.TestService" />
      ...
  </application>
</manifest>

The android:name attribute is the only required attribute—it specifies the class name of the service. Refer to AndroidManifest.xml at the End of this post.

Creating a started service

A started service is one that another component starts by calling startService(), which results in a call to the service’s onStartCommand() method. service should stop itself when its job is complete by calling stopSelf(), or another component can stop it by calling stopService().

An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.

Starting a service

You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService(). The Android system calls the service’s onStartCommand() method and passes it the Intent, which specifies which service to start.

For example, an activity can start the example service in the previous section (HelloService) using an explicit intent with startService(), as shown here:

Intent intent = new Intent(this, HelloService.class);
startService(intent);

The startService() method returns immediately, and the Android system calls the service’s onStartCommand() method. If the service is not already running, the system first calls onCreate(), and then it calls onStartCommand().

Stopping a service

A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another component can stop it by calling stopService().

Example of a Service

$ vim AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.TestService"
    android:versionCode="2"
    android:sharedUserId="android.uid.system"
    android:versionName="@string/setting_version_summary" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    </uses-permission>

    <application
    android:name="com.android.TestApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:uiOptions="splitActionBarWhenNarrow" >

        <service android:name="com.android.TestService" >
            <intent-filter>
                <action android:name="com.android.err" />
            </intent-filter>
        </service>

        <receiver android:name="com.android.TestBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>
$ vim TestService.java
package com.android.TestService;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

public class TestService extends Service {

    private static final String TAG = "TestService";

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

    @Override
    public void onCreate() {
        super.onCreate();
        /* One time initialisation code should go here */
    }

        /*
        /* startService(Intent) -> onCreate() -> onStartCommand()
        /* OR if onCreate() is not written,
        /* startService(Intent) -> onStartCommand()
         */

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        /* Do what you want to do when this services is started.*/
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /* Final Cleanup code should go here */
    }
}

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

1 thought on “Understanding Android Services with Example”

Leave a Comment