使用startForeground()调用为多个前台服务发送单个通知

23
我有一个应用程序,其中包含两个服务。一个服务用于使用WindowManager在其他应用程序上显示浮动(覆盖层)UI,另一个服务用于使用GooglePlayAPI进行位置跟踪。我的应用程序始终运行这些服务。
我希望这些服务不会被操作系统杀死。因此,我调用Service.startForeground()。但是,通知抽屉中会出现两个通知。
是否有办法为这两个服务使用单个通知?

安卓中的“两个通知”是什么意思? - Pramod Waghmare
@Pramod 当在Service中使用startForeground方法时,Android系统会设置有关正在运行的Service的通知。我使用了两个服务,并在这两个类中都使用了startForeground方法。 - Peter Han
一个选项是将这两个服务合并为一个单一的服务。我知道这不是回答问题的方法,但考虑到这两个服务同时启动和停止,这可能是一个适合你的选项。 - Madushan
1
你找到解决这个问题的方法了吗?我也遇到了同样的问题... - IgorGanapolsky
1个回答

38

是的,这是可能的。

如果我们看一下Service.startForeground()的签名,它接受通知ID和通知本身(请参阅文档)。因此,如果我们想要为多个前台服务使用唯一一个通知,这些服务必须共享相同的通知和通知ID。

我们可以使用单例模式来获取相同的通知和通知ID。以下是示例实现:

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;
    }
}

因此,我们可以在前台服务中使用这个类。例如,我们有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;
    }
}

只需尝试运行这些服务。哇!您可以为多个前台服务获得单个通知 ;)!


如果您使用RemoteViews来定义通知布局,仍然会遇到问题... - IgorGanapolsky
1
我应该如何同时停止两个服务的前台通知? - Ajay Jayendran
@Ajay 理想情况下,您应该有一些其他的父类(如一个 Activity)来启动这两个服务,并在适当的时候(例如 Activity 的 onDestroy 函数或 Activity 视图上的按钮点击以停止所有服务)调用 stopService() 函数。我希望这能有所帮助。 - gpsugy
我们可以同时运行多少个前台服务? - K Pradeep Kumar Reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接