Open In App

Foreground Service in Android

Last Updated : 04 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A foreground service has higher priority than other types of service. It is designed to perform long-running operations indicating service is running by providing notification to the user. Foreground services are used for tasks that require ongoing user awareness and interaction, such as playing music, tracking location, or performing downloads. By running a service in the foreground, you ensure that the system doesn’t kill the service due to memory constraints, and the user is aware of the ongoing operation through the notification.

Step-by-Step Implementation

To create a foreground service in Android, you need to follow these steps:

Step 1. Create a new class that extends the Service class and overrides its methods. This will be your foreground service implementation. For example:

Kotlin




class MyService: Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }
  
    override fun onCreate() {
        super.onCreate()
    }
  
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val name=intent?.getStringExtra("name")
        Toast.makeText(
            applicationContext, "Service has started running in the background",
            Toast.LENGTH_SHORT
        ).show()
        if (name != null) {
            Log.d("Service Name",name)
        }
        Log.d("Service Status","Starting Service")
        for (i in 1..10)
        {
            Thread.sleep(100)
            Log.d("Status", "Service $i")
        }
        stopSelf()
        return START_STICKY
    }
  
    override fun stopService(name: Intent?): Boolean {
        Log.d("Stopping","Stopping Service")
  
        return super.stopService(name)
    }
  
    override fun onDestroy() {
        Toast.makeText(
            applicationContext, "Service execution completed",
            Toast.LENGTH_SHORT
        ).show()
        Log.d("Stopped","Service Stopped")
        super.onDestroy()
    }
  
}


Step 2. In your AndroidManifest.xml file, declare the service as a separate component inside the tag. For example:

<service android:name="MyService"
tools:ignore="Instantiatable" />

Step 3. Start the foreground service from your activity or other parts of your app using an intent:

Kotlin




class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        val button: Button = findViewById(R.id.button)
        button.setOnClickListener {
            val intent=Intent(this,MyService::class.java)
            intent.putExtra("name","Geek for Geeks")
            startService(intent)
        }
    }
}


Output:

Screenshot_20230708_201522

Logs:

2023-07-08 20:14:27.283 17612-17612/com.example.foreground D/Service Name: Geek for Geeks

2023-07-08 20:14:27.283 17612-17612/com.example.foreground D/Service Status: Starting Service

2023-07-08 20:14:27.389 17612-17612/com.example.foreground D/Status: Service 1

2023-07-08 20:14:27.493 17612-17612/com.example.foreground D/Status: Service 2

2023-07-08 20:14:27.599 17612-17612/com.example.foreground D/Status: Service 3

2023-07-08 20:14:27.701 17612-17612/com.example.foreground D/Status: Service 4

2023-07-08 20:14:27.807 17612-17612/com.example.foreground D/Status: Service 5

2023-07-08 20:14:27.911 17612-17612/com.example.foreground D/Status: Service 6

2023-07-08 20:14:28.014 17612-17612/com.example.foreground D/Status: Service 7

2023-07-08 20:14:28.118 17612-17612/com.example.foreground D/Status: Service 8

2023-07-08 20:14:28.221 17612-17612/com.example.foreground D/Status: Service 9

2023-07-08 20:14:28.325 17612-17612/com.example.foreground D/Status: Service 10

2023-07-08 20:14:28.461 17612-17612/com.example.foreground D/Stopped: Service Stopped

Explanation:

  • startForegroundService() indicates system will be running in background. Once started, you can perform your long-running tasks within the service’s onStartCommand() method. Remember to call startForeground() with a notification to make the service run in the foreground.
  • stopForeground(true) is called when foreground service is not needed to remove the foreground status and notification within the service’s onDestroy() method. This allows the service to be properly stopped and cleaned up.

Note: Starting from Android 10 (API level 29), foreground services have some additional restrictions to prevent abuse. You may need to request the FOREGROUND_SERVICE permission in your app’s manifest and display a system-level notification to the user when starting a foreground service. Make sure to review the official Android documentation and guidelines for foreground services for the specific requirements and best practices applicable to your target Android version.

In conclusion, a foreground service in Android is a type of service that runs with higher priority than regular background services. It is used for long-running operations that require ongoing user awareness and interaction. By running a service in the foreground, you ensure that the service continues to run even when the app is in the background, and you provide a persistent notification to the user indicating the ongoing operation.

To create a foreground service, you need to extend the Service class, override its methods, and implement the desired functionality. You should call startForeground() with a notification to indicate that your service is running in the foreground. This notification keeps the user informed about the ongoing operation. When the service is no longer needed, you can call stopForeground(true) to remove the foreground status and notification.

However, starting from Android 10 (API level 29), foreground services have some additional restrictions to prevent abuse. You may need to request the FOREGROUND_SERVICE permission and display a system-level notification when starting a foreground service. It’s crucial to review the official Android documentation and guidelines for foreground services to ensure compliance with the latest requirements and best practices for your target Android version.

Overall, foreground services are a powerful tool in Android for running long-lasting operations while keeping the user informed and engaged through persistent notifications.



Similar Reads

Difference Between Foreground Service vs Activity in Android
A Service is a component of an application that may conduct long-running activities in the background. It does not have a graphical user interface. A service that has been started may continue to run for some time after the user changes to another program. A component can also bind to a service in order to communicate with it and even execute inter
3 min read
How to Handle Foreground Services in Android?
Regardless of the target SDK version, users can perform a workflow from the notification drawer to terminate an app that is running foreground services as of Android 13 (API level 33). Foreground Services (FGS) Task Manager is a newly introduced API in Android 13 that lets you put your system on a check to see if your system is being run after heav
4 min read
What is Accessibility Service in Android?
Android Framework provides a feature of Accessibility services that are designed in a way that provides an alternative way to communicate to the user on the application's behalf. Users with disabilities can use Android devices and applications with the help of an Accessibility Service. It's a long-running privileged service that allows people to co
3 min read
Difference Between Service and IntentService in Android
We all come across a variety of background-running mobile applications in our daily lives. Furthermore, in many applications, such tasks are done without the use of a user interface, i.e. the task is completed in the context. For example, our mobile device's Music app or any other Music app runs in the background, enabling you to use any other app
3 min read
How to Create an Accessibility Service in Android with Example?
Accessibility service is like a magic wand provided by the Android Framework. Although the sole purpose of the Accessibility service is to provide differently-abled an ease to access to their device, it can also be used to implement some functionalities that can help any user in his day-to-day phone usage. It is highly recommended that you should f
6 min read
Service vs IntentService in Android
We all come across a variety of mobile applications that operate in the background on a daily basis. Furthermore, in many apps, certain activities are carried out without the use of any UI, i.e. the work is carried out in the background. For example, the Music app on our mobile device or any other Music app runs in the background, and you may use a
3 min read
Android Jetpack Compose: Use Clipboard Service
Many times in the android application we want to provide an easy functionality within our android application so that users can simply copy the text from the TextView or text field to the clipboard and we can paste that text into another application of google search bar. In this article, we will take a look at How to use Clipboard manager in androi
5 min read
Intent Service in Android with Example
An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as "Intents") on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it. An IntentService in Java and Kotlin: C/C++ Code class MyIntentService : IntentService(&quot;MyIntentService&quot;
5 min read
Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Se
5 min read
Android | Android Application File Structure
It is very important to know about the basics of Android Studio's file structure. In this article, some important files/folders, and their significance is explained for the easy understanding of the Android studio work environment. In the below image, several important files are marked: All of the files marked in the above image are explained below
3 min read
Article Tags :