[英]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.