Android Service Tutorial for Background Processes
Android Service Tutorial for Background Processes

What is Android Service

Starting with what basically is a service. A service is a component of an application that is capable of performing operations in the background without directly interacting with the user. Some component of application starts the service, which then continues to run in the background and keeps on running even if the user switches to another application or the application is destroyed. A service has no UI (User Interface). Some other component of the application can also bind the service, interacting with it and performing IPC (Inter Process Communication).
Examples of services are playing music in the background or handling transactions over the network.
This video practically explains an Android Service:

ANDROID SERVICE EXAMPLE

Now let’s get to the step by step procedure for creating a service.

CREATING A NEW ANDROID PROJECT

First start by creating a new Android Studio Project:

Create New Android Project
Create New Android Project

USER INTERFACE (UI)

Inside the activity_main.xml, create two buttons by dragging the button icon from the pallete. One button will be used to start the service and the other to stop. Name them accordingly. You can use the following xml code: activity_main.xml

<?XML VERSION="1.0" ENCODING="UTF-8"?>
<RELATIVELAYOUT XMLNS:ANDROID="HTTP://SCHEMAS.ANDROID.COM/APK/RES/ANDROID"
XMLNS:TOOLS="HTTP://SCHEMAS.ANDROID.COM/TOOLS"
ANDROID:ID="@+ID/ACTIVITY_MAIN"
ANDROID:LAYOUT_WIDTH="MATCH_PARENT"
ANDROID:LAYOUT_HEIGHT="MATCH_PARENT"
ANDROID:PADDINGBOTTOM="@DIMEN/ACTIVITY_VERTICAL_MARGIN"
ANDROID:PADDINGLEFT="@DIMEN/ACTIVITY_HORIZONTAL_MARGIN"
ANDROID:PADDINGRIGHT="@DIMEN/ACTIVITY_HORIZONTAL_MARGIN"
ANDROID:PADDINGTOP="@DIMEN/ACTIVITY_VERTICAL_MARGIN"
TOOLS:CONTEXT="BUZZMYCODE.COM.MAINACTIVITY">

<LINEARLAYOUT
ANDROID:LAYOUT_WIDTH="MATCH_PARENT"
ANDROID:LAYOUT_HEIGHT="WRAP_CONTENT"
ANDROID:LAYOUT_CENTERVERTICAL="TRUE"
ANDROID:ORIENTATION="VERTICAL">

<BUTTON
ANDROID:ID="@+ID/BUTTONSTART"
ANDROID:LAYOUT_WIDTH="MATCH_PARENT"
ANDROID:LAYOUT_HEIGHT="WRAP_CONTENT"
ANDROID:LAYOUT_WEIGHT="1"
ANDROID:TEXT="START SERVICE" />

<BUTTON
ANDROID:ID="@+ID/BUTTONSTOP"
ANDROID:LAYOUT_WIDTH="MATCH_PARENT"
ANDROID:LAYOUT_HEIGHT="WRAP_CONTENT"
ANDROID:LAYOUT_WEIGHT="1"
ANDROID:TEXT="STOP SERVICE" />

</LINEARLAYOUT>

</RELATIVELAYOUT>

 

The final layout should look something like this:

Front UI Android Service Example
Front UI Android Service Example

Use this code in the MainActivity.java which will perform event handling by adding functionalities behind each button to start and stop the service respectively:

MainActivity.java:

package buzzmycode.com;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //button objects 
    private Button buttonStart;
    private Button buttonStop;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //getting buttons from xml
        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
 
        //attaching onclicklistener to buttons
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        if (view == buttonStart) {
            //start the service here
        } else if (view == buttonStop) {
            //stop the service here
        }
    }
}

CREATING A SERVICE:

To begin creating a service, first create a subclass ‘MyService’ extending from the main class ‘Service’. Then declare the service in the AndroidManifest.xml file as follows:

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

CALLBACK METHODS:

Next we have to override some callback methods. A little explanation of these methods is given as follows:

  • onStartCommand()

The system will invoke this method by calling the startService(). Any activity can start this service. And once the service starts, it will continue to run in the background.

The system will invoke this method by calling bindService(). It is used only when you want to bind the service with an activity, i.e. enabling interaction between the service and activity so that the service returns something to the activity. However if you don’t want to implement binding, then you can return null on this method.

The system will invoke this method only at the start, when the service is first created.

The system will invoke this method when the service is no longer in use and is being destroyed. This method cleans up resources such as threads, receivers or registered listeners.

OVERRIDING METHODS IN CODE:

These methods have been overridden in the following code:

(This code will play the ringtone inside the onStartCommand() so the ringtone will start playing on the start of the service, until it is stopped).

MyService.java

package buzzmycode.com;
 
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
 
/**
* Created by AASIM on 12/30/2016.
*/
 
public class MyService extends Service {
    //creating a mediaplayer object
    private MediaPlayer player;
 
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //getting systems default ringtone
        player = MediaPlayer.create(this,
                Settings.System.DEFAULT_RINGTONE_URI);
        //setting loop play to true
        //this will make the ringtone continuously playing
        player.setLooping(true);
 
        //staring the player
        player.start();
 
        //we have some options for service
        //start sticky means service will be explicity started and stopped
        return START_STICKY;
    }
 
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        //stopping the player when service is destroyed
        player.stop();
    }
}

SERVICE DEFINED IN MANIFEST:

The service also needs to be defined in the AndroidManifest.xml, as follows:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="buzzmycode.com">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- defining the service class here --> 
        <service android:name=".MyService" />
    </application>
 
</manifest>

SERVICE STOPPED AND STARTED:

Modify the MainActivity.java as shown in code. On tapping the Start Service button, the ringtone will start ringing and will continue doing so in the background until Stop Service button is tapped.

MainActivity.java

package buzzmycode.com;
 
import android.content.Intent;
import android.media.MediaPlayer;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //button objects
    private Button buttonStart;
    private Button buttonStop;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //getting buttons from xml
        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
 
        //attaching onclicklistener to buttons
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        if (view == buttonStart) {
            //starting service
            startService(new Intent(this, MyService.class));
        } else if (view == buttonStop) {
            //stopping service 
            stopService(new Intent(this, MyService.class));
        }
    }
}

And you’re done! Hope that this article clearly explains you the Android Service.