For Android Developers, a Service is a component that runs on the background to perform long-running tasks.
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.
Adding the service to the app
Now that we have our Background Service, we need to let the app know about this service.
Starting the Service
The next step is to start the service.
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.
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.
If we run the app, the service should start. However, if we terminate the app, it will stop.
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.
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().
In the onCreate() method, check if the service is not running first. If it is not running, we want to start the service.
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.
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.
If we run the app and then restart the device the service should start up automatically on its own.