Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Notification for multiple Foreground Services using startForeground() call

Tags:

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?

like image 300
Peter Han Avatar asked Jun 17 '16 11:06

Peter Han


1 Answers

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

like image 151
Riandy Rahman Nugraha Avatar answered Nov 26 '22 13:11

Riandy Rahman Nugraha