Yes it is possible.
If we look at the signature of Service.startForeground (), it accepts both the notification identifier and the notification itself ( see the documentation ). Therefore, if we want to have only one notification for several front-end services, these services must have the same notification and notification identifier.
We can use singleton pattern to get the same notification identifier and notification. Here is an example implementation:
NotificationCreator.java
public class NotificationCreator { private static final int NOTIFICATION_ID = 1094; private static Notification notification; public static Notification getNotification(Context context) { if(notification == null) { notification = new NotificationCompat.Builder(context) .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 front services. For example, we have MyFirstService.java and 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 start these services. Voila! You have one notification for several foreground services;)!
source share