是的,这是可能的。
如果我们看一下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;
}
}
只需尝试运行这些服务。哇!您可以为多个前台服务获得单个通知 ;)!