我希望在 Worker 后台运行时显示通知。我可以使用类似以下代码的东西来实现:
override suspend fun doWork(): Result {
val manager = NotificationManagerCompat.from(applicationContext)
val channel = "some_channel"
val id = 15
val builder = NotificationCompat.Builder(applicationContext, channel)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
manager.createNotificationChannel(NotificationChannel(channel, "DefaultName", NotificationManager.IMPORTANCE_LOW))
builder
.setOnlyAlertOnce(true)
.setOngoing(true)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setTicker("Background Task")
.setContentText("Starting")
.setProgress(0, 0, true)
setForeground(ForegroundInfo(id, builder.build()))
delay(500)
manager.notify(id, builder.setContentText("Progress A").setProgress(20, 0, false).build())
for (i in 1..20) {
delay(100)
manager.notify(id, builder.setProgress(20, i, false).build())
}
delay(500)
manager.notify(id, builder.setContentText("Progress B").setProgress(2, 0, false).build())
delay(1000)
manager.notify(id, builder.setProgress(2, 1, false).build())
delay(1000)
manager.notify(id, builder.setProgress(2, 2, false).build())
delay(1000)
manager.notify(id, builder.setContentText("Done!").setProgress(0, 0, false).build())
delay(500)
return Result.success()
}
但我也希望在通知中显示工作者的结果,并使其保持到用户查看和清除为止,但是通知总是在工作结束时被清除。
我该如何保持通知的活性? .setOngoing(true)
和 .setAutoCancel(false)
没有起到帮助作用。