【问题标题】:How to show multiple notifications in Foreground Service?如何在前台服务中显示多个通知?
【发布时间】:2023-01-18 17:58:11
【问题描述】:

我正在制作一个笔记应用程序,该应用程序可以选择在通知中固定笔记。
我正在使用前台服务,但问题是当我想固定多个音符时,第二个通知会替换第一个。
我使用每个笔记的唯一 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)
        }
    }
}

【问题讨论】:

  • 实际上为什么要为此提供服务?为什么不简单地显示通知并将其取消取消
  • @Sambhav.K 好吧,我不希望当用户清除所有通知或只是滑动通知时通知被取消。这就像一个提醒,只有在您按下完成按钮或其他东西时才会被解雇......
  • 行。我可以给那件事一个答案。你要我这样做吗?

标签: android kotlin android-service


【解决方案1】:

您可以使用 startForeground(notifyId.toInt(), notificationBuilder) 在 onCreate 服务方法中,然后在 onStartCommand 中使用 notificationManager.notify(notifyId.toInt(), notificationBuilder);

基本上你只需要使用 startForeground 一次,然后你需要使用通知管理器来显示通知。这样你就可以显示所有通知并且都在使用前台服务

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多