The Background Service in Android is mostly used when a task which doesn’t requires any user interaction has to be performed. For example when the data has to be synced to the cloud storage.
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
This service does not notify the user about the background tasks which are being performed. Also this kind of service is seen in action even if the application is not running actively. A background service can run indefinitely, even if the component that started it has been destroyed. – android.com
Understanding the Lifecycle of a Background Service in Android
The background services have two possible ways to complete its life cycle which are give below :
- Started Service (a.k.a. Unbounded Service)
- Bounded Service
Started (Unbounded) Service
Started service is started when an application component calls a startService() method. Once the service is initiated, it can run continuously even if the component which started the service is being destroyed. This service is seen in the Gmail application when it syncs the data in the background. The sync operation will still run if we close the application from the background. This service can stop by calling stopService() method.
Below is the lifecycle for Started Service.
Bounded Service
The Bounded service is started when an application component calls bindService() method. The service started using bindService() is linked with the component from which we have started that service. This service is stopped when the component linked to that service is unbind. This service is seen in the Music player application when the music is being played in the background of the application and when we close the application from the background the component bound with the service unbounds and hence the service stops. This service can stop by calling the unbindService() method.
A service can be created in an Android application by simply extending a java class with a service. To perform various operations on services within our application there are some callbacks methods which we need to override. These methods are listed in the table below.
Method | Description |
onStartCommand() | This method is called by android service when activity requests to start a service using startService() method. |
onBind() | This method is required to implement an android service within an android application. When an application calls bind service method to bind itself with service. User interface is also required to communicate with service by returning an IBinder object. |
onUnbind() | This method is called when the component linked to that service is disconnected. |
onRebind() | This method is called when all the components are disconnected from the service and there is a need to connect the service with new components. |
onCreate() | When a service is being created this method is called. |
onDestroy() | When a service is not being used this method is called just before the service destroys. |
Project Example for implementation of Services
We will be creating a project in Android studio in which we will be implementing service within our Android application. For implementing service in our application we will be creating a simple audio player in which we will be playing our sample audio.
We will be playing this audio using the service so that the audio will be played in the background as well. Below is the step by step procedure which we will be following for implementing services in Android.
Step 1 : Create a new project in Android studio
Open android studio in that we can get to see an option to create a new Android studio project. We have to click on that opinion and we will get to see a screen to Select a Project template in that screen we have to select an Empty activity.
After selecting empty activity we have to click on next we will be navigated to Configure your project screen. Inside this screen we have to simply specify our Project name and make sure to select the programming language as java.
After that we have to simply click on the Finish option to create our new Android studio project.
Step 2 : Working with activity_main.xml
Navigate to app > res > main > layout > activity_main.xml and add the below code in it. Comments are added in each section of code to get to know in detail.
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<!--text view for adding a simple heading-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:gravity="center"
android:text="Services in Android"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp" />
<!--linear layout for aligning the buttons horizontally-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idTVHeading"
android:layout_marginStart="10dp"
android:layout_marginTop="100dp"
android:layout_marginEnd="10dp"
android:orientation="horizontal"
android:weightSum="2">
<!--button for starting our service-->
<Button
android:id="@+id/idBtnStartService"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_weight="1"
android:text="Start Service"
android:textAllCaps="false" />
<!--button for stopping our service-->
<Button
android:id="@+id/idBtnStopService"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_weight="1"
android:text="Stop Service"
android:textAllCaps="false" />
</LinearLayout>
</RelativeLayout>
Step 3 : Creating a new java class for implementing service
Navigate to app > java > your app’s package name. Right click on it and you will get to see the New>Java class. Specify the class name as Background Service and add the below code in it. Comments are added in each section of code to get to know in detail.
package com.androiddvlpr.spotifyapp;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.IOException;
public class BackgroundService extends Service {
//creating a variable for media player.
private MediaPlayer mediaPlayer;
//on start command method will be called for starting our service.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//on below line we are creating a string for specifying media url.
String mediaUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
// on below line we are initialising our media player.
mediaPlayer = new MediaPlayer();
//on below line we are specifying audio stream type in this we are specifying stream type as stream music.
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//on below line we are specifying try and catch block for playing media player.
try {
//on below line we are specifying data source.
mediaPlayer.setDataSource(mediaUrl);
//on below line we are preparing our media player.
mediaPlayer.prepare();
//on below line we are starting our media player.
mediaPlayer.start();
} catch (IOException e) {
//on below line we are catching our exception.
e.printStackTrace();
}
//on below line we are displaying a simple toast message.
Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
//on below line we are returning start sticky.
return START_STICKY;
}
//on destroy method will be called when the service is destroyed.
@Override
public void onDestroy() {
super.onDestroy();
//inside on destroy method we are stopping our media player.
mediaPlayer.stop();
}
//below is the onBind method.
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Step 3 : Specifying permissions and our service in AndroidManifest.xml
Navigate to app > manifest > AndroidManifest.xml and inside the manifest tag add below permissions for accessing the internet and network state. As we will be using an audio URL for playing an audio from the URL.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
After adding the permissions we have to specify the service class inside our AndroidManifest.xml. Add the below line of code in the application tag. This will be use to add our service in our AndroidManifest.xml.
Step 5 : Working with MainActivity.java file
Navigate to app > java > your app’s package name > MainActivity.java file and add below code to it. Comments are added in each section of code to get to know in detail.
package com.androiddvlpr.spotifyapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
//creating variables for 2 buttons start and stop button.
private Button startBtn, stopBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing 2 buttons with their ids.
startBtn = findViewById(R.id.idBtnStartService);
stopBtn = findViewById(R.id.idBtnStopService);
//adding on click listner for our start button on below line.
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//inside on click method we are starting our service on below line.
//inside this we are simply calling start service method and inside this we have to specify the service class which we have created.
startService(new Intent(MainActivity.this, BackgroundService.class));
//on below line we are displaying a simple toast message.
Toast.makeText(MainActivity.this, "Audio started playing..", Toast.LENGTH_SHORT).show();
}
});
//adding on click listner for our stop button on below line.
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//inside on click method we will be stopping our service on below line.
//inside this method we are simply calling stop service method and inside this we have to specify the service class which we have created.
stopService(new Intent(MainActivity.this, BackgroundService.class));
//on below line we are displaying a simple toast message.
Toast.makeText(MainActivity.this, "Audio stopped playing..", Toast.LENGTH_SHORT).show();
}
});
}
}
Now we have to simply run our application to see the output of the application.
Learn more about Android Background IntentService from WhatsApp case study