使用startForeground()调用的多个Foreground Services的单一通知

Pet*_*Han 13 android android-service android-notifications

我有一个有两个服务的应用程序.

一个用于在其他应用程序上显示用于浮动(叠加)的UI WindowManager.另一种是使用位置跟踪GooglePlayAPI.我的应用总是运行这些服务.

我希望这些服务不被操作系统杀死.所以我打电话Service.startForeground().但是,通知抽屉中有两个通知.

有没有办法为这两种服务使用单一通知?

小智 22

对的,这是可能的.

如果我们看一下Service.startForeground()签名,它接受通知id和通知本身(参见文档).因此,如果我们想要只有一个前台服务的单一通知,这些服务必须共享相同的通知和通知ID.

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我们可以在前台服务中使用此类.例如,我们有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

试着运行这些服务.瞧!您有多个前台服务的单一通知;)!