【发布时间】: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