Android Foreground Service Tutorial

Android service not only can running in the background, it also possible running in the foreground by using notification and startForeground() method. There have a service called Android Foreground Service is the long running foreground service that give a running notification UI to the user. Besides that, it can let user perform some action on the notification and it not bind to any component in the android. For a good example, we can use foreground service to play music and show it in the notification while user switch to another app. In this tutorial, I will give you all the steps to create the foreground service in android. It just take around 10 minutes to complete the foreground service.

Creating a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “ForegroundServiceExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Activity” and Click Next button
5. Lastly, press finish button.

Edit activity_main.xml layout

Go to your activity_main.xml insert the below code. I add two button inside the linear layout.

Create a custom notification layout

Right click layout folder and create a new xml file and name it as notification. It is to customize the notification that you want.

Create a Service

Right click you package name and create a new service activity name it as ForegroundService.

Edit class

In your add the notification and broadcast receiver in your service.

Edit class

Go to your and copy paste the following code.

Run your Project

Now, you can start your project in your android device and test the foreground service.

(Android Foreground Service)

Source Code

(Visited 5,600 times, 1 visits today)

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

3 Responses

  1. Didn’t you miss the part about AndroidManifest.xml?

  2. says:

    It is really a nice and useful piece of info.
    I am glad thwt you shared this useful information wwith us.
    Please stay us informed like this. Thank you for sharing.

  3. Rohit Sharma says:

    Really helpful. Thankyou so much

Leave a Reply

Your email address will not be published. Required fields are marked *