Single Notification for multiple Foreground Services using startForeground() call

痴心易碎 提交于 2019-11-30 12:30:06

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!