So I'm not sure where/how to implement this method to make my service run in the foreground. Currently I start my service by the following in another activity:

Intent i = new Intent(context, myService.class); 

And then in myServices' onCreate() I try the startForeground()...?

Notification notification = new Notification();
startForeground(1, notification);

So yeah I'm a bit lost and unsure of how to implement this.

Solution 1

I'd start by completely filling in the Notification. Here is a sample project demonstrating the use of startForeground().

Solution 2

From your main activity, start the service with the following code:

Intent i = new Intent(context, MyService.class); 

Then in your service for onCreate() you would build your notification and set it as foreground like so:

Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("My Awesome App")
                .setContentText("Doing some work...")

startForeground(1337, notification);

Solution 3

Solution for Oreo 8.1

I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:


override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this,

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    } else {


override fun onCreate() {

private fun startForeground() {

    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            } else {
                // If earlier version channel ID is not used

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
    startForeground(101, notification)

private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    return channelId


public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;

    public void onCreate() {

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)

        startForeground(ID_SERVICE, notification);
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        return channelId;

Solution 4

This is my code to set the service to foreground:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)

    startForeground(NOTIFICATION_ID, notification);


I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

To remove the notification, just call the stopForeground(true);

It is called in the onStartCommand(). Please refer to my code at :

Solution 5

In addition to RAWA answer, this peace of code:

} else {

You can change to:

ContextCompat.startForegroundService(context, yourIntent);

If you will look inside this method then you can see that this method do all checking work for you.

Solution 6

If you want to make IntentService a Foreground Service

then you should override onHandleIntent()like this

protected void onHandleIntent(@Nullable Intent intent) {

    startForeground(FOREGROUND_ID,getNotification());     //<-- Makes Foreground

   // Do something

    stopForeground(true);                                // <-- Makes it again a normal Service                         



How to make notification ?

simple. Here is the getNotification() Method

public Notification getNotification()

    Intent intent = new Intent(this, SecondActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

    NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);

    foregroundNotification.setContentTitle("MY Foreground Notification")
            .setContentText("This is the first foreground notification Peace")


Deeper Understanding

What happens when a service becomes a foreground service

This happens

What is a foreground Service ?

A foreground service,

  • makes sure that user is actively aware of that something is going on in the background by providing the notification.

  • (most importantly) is not killed by System when it runs low on memory

A use case of foreground service

Implementing song download functionality in a Music App

Solution 7

Add given code Service class for "OS >= Build.VERSION_CODES.O" in onCreate()

public void onCreate(){


    //For creating the Foreground Service
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? getNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
           // .setPriority(PRIORITY_MIN)

    startForeground(110, notification);

private String getNotificationChannel(NotificationManager notificationManager){
    String channelId = "channelid";
    String channelName = getResources().getString(R.string.app_name);
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    return channelId;

Add this permission in manifest file:

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

Solution 8

Handle intent on startCommand of service by using.


This call will remove the service from foreground state, allowing it to be killed if more memory is needed. This does not stop the service from running. For that, you need to call stopSelf() or related methods.

Passing value true or false indicated if you want to remove the notification or not.

val ACTION_STOP_SERVICE = "stop_service"
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)
    if (ACTION_STOP_SERVICE == intent.action) {
    } else {
        //Start your task

        //Send forground notification that a service will run in background.
    return Service.START_NOT_STICKY

Handle your task when on destroy is called by stopSelf().

override fun onDestroy() {
    //Stop whatever you started

Create a notification to keep the service running in foreground.

//This is from Util class so as not to cloud your service
fun sendServiceNotification(myService: Service) {
    val notificationTitle = "Service running"
    val notificationContent = "<My app> is using <service name> "
    val actionButtonText = "Stop"
    //Check android version and create channel for Android O and above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        //You can do this on your own
    //Build notification
    val notificationBuilder = NotificationCompat.Builder(applicationContext, CHANNEL_ID_SERVICE)
    //Add stop button on notification
    val pStopSelf = createStopButtonIntent(myService)
    notificationBuilder.addAction(R.drawable.ic_location, actionButtonText, pStopSelf)
    //Build notification
    val notificationManagerCompact = NotificationManagerCompat.from(applicationContext)
    val notification =
    //Start notification in foreground to let user know which service is running.
    myService.startForeground(NOTIFICATION_ID_SERVICE, notification)
    //Send notification
    notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notification)

Give a stop button on notification to stop the service when user needs.

 * Function to create stop button intent to stop the service.
private fun createStopButtonIntent(myService: Service): PendingIntent? {
    val stopSelf = Intent(applicationContext,
    stopSelf.action = ACTION_STOP_SERVICE
    return PendingIntent.getService(myService, 0,
            stopSelf, PendingIntent.FLAG_CANCEL_CURRENT)

Solution 9

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground.

If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground.

Once the service has been created, the service must call its startForeground() method within five seconds.

Solution 10

In my case It was totally different since I was not having activity to launch the service in Oreo.

Below are the steps which I used to resolve this foreground service issue -

public class SocketService extends Service {
    private String TAG = this.getClass().getSimpleName();

    public void onCreate() {
        Log.d(TAG, "Inside onCreate() API");
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setContentTitle("Notification Alert, Click Me!");
            mBuilder.setContentText("Hi, This is Android Notification Detail!");
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // notificationID allows you to update the notification later on.
            startForeground(100, mBuilder.mNotification);
        Toast.makeText(getApplicationContext(), "inside onCreate()", Toast.LENGTH_LONG).show();

    public int onStartCommand(Intent resultIntent, int resultCode, int startId) {
        Log.d(TAG, "inside onStartCommand() API");

        return startId;

    public void onDestroy() {
        Log.d(TAG, "inside onDestroy() API");


    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;

And after that to initiate this service I triggered below cmd -

adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService

So this helps me to start service without activity on Oreo devices :)

Solution 11

@mikebertiean solution almost did the trick, but I had this problem with additional twist -- I use Gingerbread system and I didn't want to add some extra package just to run notification. Finally I found:

then I hit additional problem -- notification simply kills my app when it runs (how to solve this problem: Android: How to avoid that clicking on a Notification calls onCreate()), so in total my code in service looks like this (C#/Xamarin):

Intent notificationIntent = new Intent(this, typeof(MainActivity));
// make the changes to manifest as well
notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(Resource.Drawable.Icon, "Starting service");
notification.SetLatestEventInfo(this, "MyApp", "Monitoring...", pendingIntent);
StartForeground(1337, notification);