[英]How to show multiple notifications in Foreground Service?
I'm making a note app that has an option for pinning notes in the notifications.我正在制作一个笔记应用程序,该应用程序可以选择在通知中固定笔记。
I'm using foreground service but the problem is when I want to pin more than one note, the notification for the second one replaces the first one.我正在使用前台服务,但问题是当我想固定多个音符时,第二个通知会替换第一个。
I'm using each note's unique ID as notificationId
.我使用每个笔记的唯一 ID 作为
notificationId
。 Here's my code:这是我的代码:
class MyService : Service() {
lateinit var note: Note
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
note = intent.getParcelableExtra(NOTIFICATION_MESSAGE_EXTRA)!!
showNotification()
return START_STICKY
}
private fun showNotification() {
val notificationIntent = Intent(this, MyService::class.java)
val pendingIntent = PendingIntent.getActivity(
this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Title")
.setContentText(note.noteText)
.setContentIntent(pendingIntent)
.setGroup(CHANNEL_GROUP_KEY)
.build()
startForeground(note.id, notification)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
)
val notificationManager =
getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
}
}
You can done this by using startForeground(notifyId.toInt(), notificationBuilder) in onCreate method of service and then in onStartCommand use notificationManager.notify(notifyId.toInt(), notificationBuilder);您可以通过在服务的 onCreate 方法中使用 startForeground(notifyId.toInt(), notificationBuilder) 然后在 onStartCommand 中使用 notificationManager.notify(notifyId.toInt(), notificationBuilder) 来完成此操作;
Basically you need to only use startForeground once and then you need to use notification manager for showing notification.基本上你只需要使用 startForeground 一次,然后你需要使用通知管理器来显示通知。 That way you are able to show all the notifications and all are using foreground service
这样你就可以显示所有通知并且都在使用前台服务
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.