Twitter LogoFacebook Logo
Understanding and Using Services in Android: Background & Foreground Services
Hello, in this video, I will show you how to utilize Background and Foreground Services in Android.
By: King

Hello, in this tutorial, I will show you how to utilize Background and Foreground Services in Android.

There are 3 types of services in Android:

(1) Background
(2) Foreground
(3) Bound

Each of these terms are misleading because it is not describing the behavior of how each service are used, but it is describing how they are terminated.

For Android Developers, a Service is a component that runs on the background to perform long-running tasks.

A Background Service is a service that runs only when the app is running so it’ll get terminated when the app is terminated.

A Foreground Service is a service that stays alive even when the app is terminated.

And a Bound Service is a service that runs only if the component it is bound to is still active.

Let’s see how we can create a Background Service.

Creating a Background Service

To create a Background Service, (1) create a new Class and have it extend the Service class. (2) Inside the class, override the onBind() and onStartCommand() methods. 

The onStartCommand() method is called every time we start the service either by calling startService() or startForegroundService(). This is where we want to define what the service will do. 

For now, we’ll create a thread that’ll print a message to the terminal every 2 seconds. 

Adding the service to the app

Now that we have our Background Service, we need to let the app know about this service. 


Go to the manifests file. Inside the application element, add a service element and use the android:name attribute to add the service to the app.

Starting the Service

The next step is to start the service. 


Go to the MainActivity file. In the onCreate() method, create an Intent for the Background Service.

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

     Intent serviceIntent = new Intent(this, MyBackgroundService.class);

}

Call startService() and pass in the intent.

startService(serviceIntent);

If we run the app and look at the terminal, a message will be displayed every 2 seconds. 


If we minimize the app, the service will continue to run. 

If we terminate the app, it will stop.

Creating Foreground Services

Now let’s see how we create a Foreground Service. Create a new class and have it extend the Service class. 

Override the onBind() and onStartCommand() methods. 

Inside the onStartCommand() method, copy the code from the BackgroundService and paste it inside. 

Go to the manifests file and add the service to the app. 

In order for us to use Foreground Services, we need to add the FOREGROUND_SERVICE permission in the manifests file to enable it. 

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

Starting the Foreground Service

Now we need to start the service. 


Go to the MainActivity file. In the onCreate() method, replace the BackgroundService class with the ForegroundService class for the intent. 

Instead of calling startService(), call startForegroundService(). 

Intent serviceIntent = new Intent(this, MyForegroundService.class);

startForegroundService(serviceIntent);

If we run the app, the service should start. However, if we terminate the app, it will stop. 


This is because we have not put the service in the Foreground yet. Calling startForegroundService() only starts the service, we still need to put it in the Foreground state. 

Go back to the Foreground Service class. In the onStartCommand() method, call startForeground(). 

public int onStartCommand(Intent intent, int flags, int startId) {
    ...

    startForeground(ID, NOTIFICATION);

    return super.onStartCommand(intent, flags, startId);
}

It takes 2 arguments. An id for the notification and the notification itself.

The reason we need to provide a notification for a Foreground Service is because we need to let the user know that there is a service from our app that is running even when the app is terminated. The notification cannot be removed until the service is terminated.

Pass in an ID and a notification object.

If we run the app and terminate the app, the service should still be running and we’ll see the notification in the notification tray.

Image from Codeible.com

Although it is working as intended, we still need to do one more thing to properly handle Foreground Services. Because they stay alive even after the app is terminated, whenever the app gets relaunched, another service will be created, and we’ll end up with multiple of the same service running at the same time.

To stop this from happening, every time we want to start the service, we need to check if it is already running first. 

Go back to the MainActivity file. Create a Boolean method call foregroundServiceRunning() and have it return false by default.

Inside the method get a reference to the ActivityManager using getSystemService(). 


Then use a For Loop and loop through all the active services that are running for the app. 

During each iteration, check if there is a service that matches our Foreground Service. If there is, return true.

In the onCreate() method, check if the service is not running first. If it is not running, we want to start the service.

if(!foregroundServiceRunning()) {

    Intent serviceIntent = new Intent(this, MyForegroundService.class);
    startForegroundService(serviceIntent);

}

If we run the app, and then terminate it, and then relaunch the app, it’ll not start the service again.

Restarting the Foreground Service on Reboot

Sometimes you may want to restart a Foreground Service when the user reboots the system. We can achieve this by using a BroadcastReceiver. 


The purpose of the Broadcast Receiver is to send or receive messages from the Android System.

When the user reboots their device, Android will send out a message telling everyone that the system was rebooted. We need to create a BroadcastReceiver to receive that message so we can restart Foreground Service.

To create a BroadcastReceiver, create a new class and have it extend the BroadcastReceiver class.

Since we want to receive the Reboot message when the system is restarted, override the onReceive() method. 

Now that we have the BroadcastReceiver class, we need to add the BroadcastReceiver in the manifests file to let the app know about it.

Go to the Manifests file. 

(1) Add a receiver element and use the android:name attribute to add the receiver. 

(2) Inside the receiver, add an intent filter element to let the app will know what the receiver will be listening for. 

(3) Add the BOOT_COIMPLETED action so it’ll listen for when the app is rebooted. 

(4) When that is done, enable the RECEIVE_BOOT_COMPLETE permission.

Now go back to the BroadcastReceiver class. In the onReceive() method, check if the action we received from the intent is equal to ACTION_BOOT_COMPLETED. If it is, we want to start the Foreground Service.

@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

        Intent serviceIntent = new Intent(context, MyForegroundService.class);
        context.startForegroundService(serviceIntent);

    }
}

If we run the app and then restart the device the service should start up automatically on its own.


Sign In