[英]How to show multiple notifications in Foreground Service?
我正在制作一个笔记应用程序,该应用程序可以选择在通知中固定笔记。
我正在使用前台服务,但问题是当我想固定多个音符时,第二个通知会替换第一个。
我使用每个笔记的唯一 ID 作为notificationId
。 这是我的代码:
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)
}
}
}
您可以通过在服务的 onCreate 方法中使用 startForeground(notifyId.toInt(), notificationBuilder) 然后在 onStartCommand 中使用 notificationManager.notify(notifyId.toInt(), notificationBuilder) 来完成此操作;
基本上你只需要使用 startForeground 一次,然后你需要使用通知管理器来显示通知。 这样你就可以显示所有通知并且都在使用前台服务
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.