在制作计时器应用的过程中,出现了一种涉及前台服务和通知的奇怪情况。该应用程序在服务中包含多个计时器。启动计时器后,服务会启动自定义CountdownTimer并在通知中更新剩余的计时器时间。没问题。问题出现在第二个计时器启动时。在这种情况下,“前台服务”通知“弹出”和“正在关闭”,因此无法看到该通知。
问题是如何将2个单独的计时器时间onTick()发布到同一通道上的同一顺序的相同通道上?
通知应显示如下:
App
1:50 remaining
0:30 remaining
这是服务中用于上下文的一些代码。计时器对象的onTick()代码(请记住,我们有多个Timer对象):
private fun createTimer(timerTime: Long, timerID: Long):EnkelTimer{
val timerID_Int = timerID.toInt()
return object : EnkelTimer(
countdownInterval = 1000,
millisInFuture = 1000 * timerTime,
id = timerID){
override fun onFinish() {
//TODO Notification that we are done
activeTimers.remove(this)
if (activeTimers.size<2){
stopForegroundService()
}
}
override fun onTick(millisUntilFinished: Long) {
startForeground(timerID_Int, notificationFromTimeRemaining(millisUntilFinished))
}
}
}
通知代码:
private fun notificationFromTimeRemaining(millisUntilFinished: Long): Notification{
val notifChannel = if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
createNotificationChannel()
} else {""}
val notifBuilder = NotificationCompat.Builder(this, notifChannel)
with(notifBuilder){
setSmallIcon(R.drawable.play)
setStyle(NotificationCompat.BigTextStyle())
setContentTitle(numberOfTimersRunningText())
setContentText("${DateUtils.formatElapsedTime(millisUntilFinished/1000)}")
setShowWhen(false)
setAutoCancel(false)
setChannelId(CHANNEL)
}
return notifBuilder.build()
}
通知渠道代码:
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel():String{
val name = "Timers"
val description = "A channel for Enkel timers"
val importance = NotificationManager.IMPORTANCE_LOW
val notificationChannel = NotificationChannel(CHANNEL, name, importance)
notificationChannel.description = description
val notificationManager: NotificationManager =
getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
return CHANNEL
}