Single notification for multiple Foreground Services using startForeground ()

I have an application that has two services.

One of them is displaying the user interface for floating (overlay) in other applications using WindowManager . Another is for tracking location using GooglePlayAPI . My application always runs these services.

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

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

+6
source share
1 answer

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;)!

+10
source

All Articles