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