当前位置:   article > 正文

android 单例通知,android – 使用startForeground()调用多个Foreground Services的单一通知...

startforeground( 通知id指定

对的,这是可能的.

如果我们看一下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;

}

}

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号