1

Below is a snippet of code in my service class.

If a user "joins a team" (operation = 0) then it create a notification with its designated specifications however if a user shares their location (operation = 1) then its supposed to create a separate foreground notification. Instead one just replaces the other.

I don't know why, they have different ID's just same channel. I've also tried separating their channel ID, still the same issue

int id = NOTIFICATION_LOCATION;
        int icon = R.drawable.ic_gps_on;
        String message = "Tap to disable location updates";

        if (operation == 0) {
            id = NOTIFICATION_RESPONDER;
            icon = R.drawable.ic_responder_icon;
            message = "Tap to leave the responding team";
        }

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_1)
                .setSmallIcon(icon)
                .setContentTitle("Location established")
                .setContentText(message)
                .setContentIntent(PendingIntent.getBroadcast(getApplicationContext(), 0, getBroadcastIntent(operation), PendingIntent.FLAG_UPDATE_CURRENT))
                .setColor(ContextCompat.getColor(getApplicationContext(), R.color.primaryColor))
                .setDefaults(Notification.DEFAULT_SOUND)
                .setVisibility(VISIBILITY_PUBLIC)
                .build();

        startForeground(id, notification);
jeanluc rotolo
  • 165
  • 1
  • 11

1 Answers1

2

The notification you manipulate with startForeground() is meant to be the one "official" notification that corresponds to the foreground service; the one that Android insists you have up at all times the service is running.

It doesn't surprise me that, if you supply a different notification channel ID on a subsequent call to startForeground(), it erases and replaces the original notification. Otherwise, you might end up with multiple foreground notifications for a single service, and things could get confusing.

Instead, just use NotificationManager.notify() to manage any notifications that occur in excess of the original foreground service notification. Use distinct IDs for these extra notifications.

A good practice is to use a fixed ID for your foreground service notification. You can still change the Notification at will; it's just easier to remember which Notification is your "official" one, when you have a fixed ID.

You can also manipulate your "official foreground service notification" using notify(); you don't have to use startForeground(). A call to startForeground() is only needed once, at the beginning, to associate the service with a specific notification ID.

greeble31
  • 4,894
  • 2
  • 16
  • 30