4

I do have a service which is started in foreground:

val notification = NotificationCompat.Builder(context)
    .setSmallIcon(R.drawable.ic_stat_notify)
    .setContentTitle(title)
    .setTicker(message)
    .setStyle(NotificationCompat.BigTextStyle().bigText(message))
    .setContentText(message)
    .setContentIntent(pendingIntent)
    .build()
startForeground(Notifications.Id.RUNNING, notification)

Note that I am not using setOngoing(true).

I found some examples and answers here at StackOveflow and some people are using setOngoing(true) and some don't. Examples:

Also, the Android documentation says:

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the Ongoing heading. This means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

And, inside the documentation, the setOngoing(true) is not being set:

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
          new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
    .setContentTitle(getText(R.string.notification_title))
    .setContentText(getText(R.string.notification_message))
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .setTicker(getText(R.string.ticker_text))
    .build();

startForeground(ONGOING_NOTIFICATION_ID, notification);

Question

What is the impact omitting the setOngoing(true)?

rsicarelli
  • 1,013
  • 1
  • 11
  • 28

1 Answers1

4

When you start a Service and run it in foreground with startForeground(int, Notification), the notification you passed get's the flag FLAG_FOREGROUND_SERVICE (see here).

Then, before your notification will actually be posted into the status bar NotificationManagerService checks if FLAG_FOREGROUND_SERVICE is set and if so it will add the flag FLAG_ONGOING_EVENT (see here) which is the same flag that will be set when you manually use setOngoing(true) (see here).

ElegyD
  • 4,393
  • 3
  • 21
  • 37
  • Is it possible though to allow the user to dismiss the notification of the foreground service just like any other notification, which would trigger the service and so we can close the service? – android developer Aug 20 '18 at 14:24