Single Notification for multiple Foreground Servic

2019-03-26 07:15发布

问题:

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?

回答1:

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 only single notification for more than one foreground services, these services must share the same notification & notification id.

We can use 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 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 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 single notification for multiple foreground services ;)!