Peter Han
Peter Han

Reputation: 241

Single Notification for multiple Foreground Services using startForeground() call

I have an app that has two services.

One is for showing UI for floating (overlay) on other apps using WindowManager. The other is for Location Tracking using GooglePlayAPI. My app always runs these services.

I want these services not to be killed by the OS. So I call Service.startForeground(). However there are two notifications in the notification drawer.

Is there a way to use a single notification for both services?

Upvotes: 24

Views: 11935

Answers (1)

Riandy Rahman Nugraha
Riandy Rahman Nugraha

Reputation: 491

Yes, it is possible.

If we take a look at Service.startForeground() signature, it accept both notification id & the notification itself (see documentation). Hence, if we want to have an only single notification for more than one foreground services, these services must share the same notification & notification id.

We can use the singleton pattern to get the same notification & notification id. Here is the example implementation:

NotificationCreator.java

public class NotificationCreator {

    private static final int NOTIFICATION_ID = 1094;
    private static final String CHANNEL_ID = "Foreground Service Channel";
    private static Notification notification;

    public static Notification getNotification(Context context) {

        if(notification == null) {

            notification = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setContentTitle("Try Foreground Service")
                    .setContentText("Yuhu..., I'm trying foreground service")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
        }

        return notification;
    }

    public static int getNotificationId() {
        return NOTIFICATION_ID;
    }
}

Thus, we can use this class in our foreground services. For example, we have MyFirstService.java & MySecondService.java:

MyFirstService.java

public class MyFirstService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(NotificationCreator.getNotificationId(),
                NotificationCreator.getNotification(this));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

MySecondService.java

public class MySecondService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(NotificationCreator.getNotificationId(),
                NotificationCreator.getNotification(this));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Just try to run these services. Voila! You have a single notification for multiple foreground services ;)!

Upvotes: 39

Related Questions