android notification kotlin

// 1. Create a notification channel
private fun createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = "Channel Name"
        val descriptionText = "Channel Description"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel("channel_id", name, importance).apply {
            description = descriptionText
        }
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

// 2. Create a notification
private fun createNotification() {
    val channelId = "channel_id"
    val notificationBuilder = NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("Notification Title")
        .setContentText("Notification Text")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    with(NotificationManagerCompat.from(this)) {
        notify(notificationId, notificationBuilder.build())
    }
}

// 3. Show the notification
private fun showNotification() {
    createNotificationChannel()
    createNotification()
}

This code creates a notification channel for devices running Android Oreo or higher to group notifications. It then builds a notification using the NotificationCompat.Builder, setting its small icon, title, text, and priority. Finally, it shows the notification by calling notify() from NotificationManagerCompat.