The setTimeOutAfter
method for notification seems not t be working. My application meets the requirement for minSdk but I do not know why the heads-up-notification dismises from the screen before time elapses.
@Singleton
class NotificationHelper @Inject constructor(
@ApplicationContext private var context: Context,
) {
companion object {
private const val NOTIFICATION_CHANNEL_ID = "NOTIFICATION_CHANNEL"
private const val NOTIFICATION_CHANNEL_NAME = "NOTIFICATION_CHANNEL_NAME"
private const val BROADCAST_REQUEST_CODE = 0
private const val NOTIFICATION_TIME_OUT = 30000L
}
fun getNotificationManager() =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
fun createNotification(
title: String,
subtitle: String = "",
): Notification {
createNotificationChannel()
return createNotificationBase(title, subtitle)
.build()
}
fun <T> createNotification(
title: String,
actionTitle: String,
buttonAction: String,
broadcastReceiver: Class<T>,
subtitle: String = ""
): Notification {
createNotificationChannel()
val intent = Intent(context, broadcastReceiver)
.apply {
action = buttonAction
}
val pendingIntent = pendingIntentWithBroadcast(intent)
return createNotificationBase(title, subtitle)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_amazon_blue_logo, actionTitle, pendingIntent)
.build()
}
fun sendNotification(notification: Notification, notificationId: Int) {
getNotificationManager().notify(notificationId, notification)
}
private fun pendingIntentWithBroadcast(intent: Intent): PendingIntent =
PendingIntent.getBroadcast(
context,
BROADCAST_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
private fun createNotificationChannel() {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
.apply {
lockscreenVisibility = Notification.VISIBILITY_PRIVATE
}
getNotificationManager().createNotificationChannel(channel)
}
private fun createNotificationBase(
title: String,
subtitle: String,
): NotificationCompat.Builder {
return NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_alexa_notification)
.setContentTitle(title)
.setContentText(subtitle)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setTimeoutAfter(NOTIFICATION_TIME_OUT)
.setOnlyAlertOnce(true)
}
fun cancelNotification(notificationId:Int) = getNotificationManager().cancel(notificationId)
}
How can I make this work?