Tuesday, October 21, 2014

Android Services - Introduction

11:42 PM

What is Service?

A service is a component that runs in background to run operation/tasks without user interaction.
i.e, a service might play music in the background while the user is in a different application, or it might fetch data over the server without blocking user interaction with in an activity.

Many Android apps need to do some things in the background when your application isn't open .
Maybe we need to periodically abstract data from server or maybe we need to have certain tasks run on an interval that is specified by users. Android Service is the best for these tasks.

Is service different from thread??

As we know services and thread are both run on background and both are run without user interaction. But they are very different in how they are applied in android application, and most importantly services is not a thread. It runs on the UI thread(User Interface thread) along with our application. Some time we have to use thread inside of services while lifting some heavy data from server in our application.

A service is usually take two state

1. Started:
It is started by activity by calling startService(), once it is started it runs on background indefinitely. It is basically used for downloading/uploading file over server (which is done for one time operation).
After its done it should stop itself.

2. Bound:

It is started by activity by calling bindService(). A bount service offers client-server interface that allow component to interact with service, send request , get result, and even do so across processes with interprocess communication(IPC).

There are two type of services 

1. Platform services:
The android Platform Services are default android system services. The Android platform provides and runs predefined system services and every Android application can use them, given the right permissions. These system services are usually exposed via a specific Manager class. To access them we need  getSystemService() method. The Context class defines several constants for accessing these services.

2. Custom Services:
Custom services allows us to design responsive applications.We can fetch the application data via it and once the application is started by the user, it can present fresh data to the users.

How to create a custom services in android app, its so simple look below.

//creating a new class for service
public class MyService extends Service {
  public IBinder onBind(Intent arg0) {
            //TODO for communication return IBinder implementation
           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();

 Calling  services in our activity....

public class MainActivity extends Activity {

     public void onCreate(Bundle savedInstanceState)

             //Start service 
startService(new Intent(getBaseContext(), MyService.class));

Finally a service needs to be declared in the AndroidManifest.xml file...like below
 <service android:name=".MyService" />

How to start Services regularly via AlarmManager?

Here is the complete example of starting Service regularly via AlarmManager to notify user through NotificationManager. For this we need to create MyService (extends IntentService), AlarmNotificationReceicer (extends BroadcastReceiver), MainActivity (extends Activity) and declare service and receiver in AndroidMinfeast.xml file...See  below.....

1. Make a Class for Service which Extends IntentService.

package com.examples.semicolon.Alarms;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;

public class MyService extends IntentService {

private AlarmManager mAlarmManager;
private Intent mNotificationReceiverIntent, mLoggerReceiverIntent;
private PendingIntent mNotificationReceiverPendingIntent,
private static final long INITIAL_ALARM_DELAY = 1 * 60 * 1000;

public MyService() {


protected void onHandleIntent(Intent intent) {

// Get the AlarmManager Service(platform services)
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

// Create PendingIntent to start the AlarmNotificationReceiver
mNotificationReceiverIntent = new Intent(MyService.this,
mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(
PlayService.this, 0, mNotificationReceiverIntent, 0);

// seting repeated alarm
SystemClock.elapsedRealtime() + INITIAL_ALARM_DELAY,
INITIAL_ALARM_DELAY, mNotificationReceiverPendingIntent);



2. Make a class for Notification which extends BroadcastReceiver

package com.examples.semicolon.Alarms;

import java.text.DateFormat;
import java.util.Date;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import course.examples.Alarms.AlarmCreate2.R;

public class AlarmNotificationReceiver extends BroadcastReceiver {
// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;
private static final String TAG = "AlarmNotificationReceiver";

// Notification Text Elements
private final CharSequence tickerText = "Are You Playing games Again!";
private final CharSequence contentTitle = "A Kind of Reminder";
private final CharSequence contentText = "Get back to studying!!";

// Notification Action Elements
private Intent mNotificationIntent;
private PendingIntent mContentIntent;

// Notification Sound and Vibration on Arrival
private Uri soundURI = Uri.parse("android.resource://com.examples.semicolon.Alarms/"
+ R.raw.alarm_rooster);
private long[] mVibratePattern = { 0, 200, 200, 300 };

public void onReceive(Context context, Intent intent) {

mNotificationIntent = new Intent(context, MainActivity.class);
mContentIntent = PendingIntent.getActivity(context, 0,
mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                 // notification building
Notification.Builder notificationBuilder = new Notification.Builder(

.setSmallIcon(android.R.drawable.stat_sys_warning)// icon from drawable

// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) context

Log.i(TAG,"Sending notification at:" + DateFormat.getDateTimeInstance().format(new                      Date()));


3. Creating  the activity and calling the service in an activity.

package com.examples.semicolon.Alarms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import course.examples.Alarms.AlarmCreate2.R;

public class MainActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
                //start the service
startService(new Intent(getBaseContext(), MyService.class));

4. Defined the Service and Receiver in AndroidManifest.xml file

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

        android:targetSdkVersion="19" />

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

        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

        <receiver android:name="com.examples.semicolon.Alarms.AlarmNotificationReceiver" />
        <service android:name="com.examples.semicolon.Alarms.PlayService" />



The output of  above code: You will receive a notification in every 1 minute of time interval even your app is not open.

Written by

We are passionate programmers. Enjoying the rich platforms of Semicolon Family of Programming languages we are proud to call ourselves Semicolon Developers.


Post a Comment


© 2013 Echo "Semicolon Developers"; Kathmandu. All rights resevered @ Semicolon Developers Network Pvt. Ltd.. Designed by Templateism

Back To Top