0

我想创建一个带有抬头功能的通知。基本上它是一个警报功能。我想用通知显示foreground。现在workmanager具有使用setForeground . 但它没有显示通知,因为我实现它如下:


@HiltWorker
class NotificationWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParams: WorkerParameters,
) : CoroutineWorker(context, workerParams) {

    override suspend fun doWork(): Result {
        Log.d(TAG, "doWork: notification worker called ")
        setForeground(createForegroundInfo())
        return Result.success()
    }

    private fun createForegroundInfo(): ForegroundInfo
    {

        val msg = "messgae "
        val id = 34


        val channelId = "show_reminder"
        val channelName = "Reminder Notification"
        val alarmSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
        val vibratePattern = longArrayOf(500, 500, 500, 500, 500, 500, 500, 500, 500)

        val customView = RemoteViews("packageName", R.layout.alarm_notification)

        customView.setTextViewText(R.id.content, msg.trim())

        val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

       

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            val  channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

...

        val builder = NotificationCompat.Builder(applicationContext,channelId)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentText(msg.trim())
            .setStyle(NotificationCompat.BigTextStyle()
                .bigText(msg.trim()))
            .setSmallIcon(R.drawable.ic_baseline_access_alarm_24)
            .setSound(alarmSound)
            .setVibrate(vibratePattern)
            .setCustomHeadsUpContentView(customView)
            .setStyle(NotificationCompat.DecoratedCustomViewStyle())

        //notificationManager.notify(id, builder.build())


        return ForegroundInfo(id,builder.build())
    }

}

调用 notificationManager.notify(id, builder.build()) 时会显示通知,但不会保持很长时间。如何让抬头通知保持很长时间?

4

0 回答 0