我是靠谱客的博主 繁荣奇迹,这篇文章主要介绍android 单例通知,android – 使用startForeground()调用多个Foreground Services的单一通知...,现在分享给大家,希望可以做个参考。

对的,这是可能的.

如果我们看一下Service.startForeground()签名,它接受通知id和&通知本身(see documentation).因此,如果我们想要只有一个前台服务的单一通知,这些服务必须共享相同的通知&通知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;

}

}

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

}

}

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

最后

以上就是繁荣奇迹最近收集整理的关于android 单例通知,android – 使用startForeground()调用多个Foreground Services的单一通知...的全部内容,更多相关android内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部