0

我必须创建一个自定义通知,例如什么是应用调用通知。如果我将自定义布局添加到 NotificationCompat Builder,则不会创建通知。下面是我创建通知的代码。创建通知

   context?.let {

        val notificationLayout = RemoteViews(it.packageName, R.layout.custom_notification_collapsed)
        val notificationLayoutExpanded = RemoteViews(it.packageName, R.layout.custom_notification)

        notificationLayout.setImageViewResource(R.id.iv_icon, R.drawable.icon)
        notificationLayout.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
        notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))

        notificationLayoutExpanded.setImageViewResource(R.id.iv_icon,R.drawable.icon)
        notificationLayoutExpanded.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
        notificationLayoutExpanded.setTextViewText(R.id.content, it.getString(R.string.text))
        notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))

        var builder = NotificationCompat.Builder(it, AppConstants.CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setTicker("Noification is created")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCustomContentView(notificationLayout)
                .setCustomBigContentView(notificationLayoutExpanded)


        var customNotificationCompat: NotificationManagerCompat = NotificationManagerCompat.from(it)
        customNotificationCompat.notify(0, builder.build())

    }

创建 Channel 并从 Application 类调用它:

    fun createNotificationChannel(context: Context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = context.getString(R.string.app_name)
        val descriptionText = context.getString(R.string.text)
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel(AppConstants.CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system
        val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}
4

0 回答 0