Show Notification in Android

A notification is a message that appears outside an application’s UI to get user attention, provide reminders, notify about events, etc. A typical notification consists of small icon, title, and content text.

Android 8.0 (API level 26) and higher versions of the platform, requires that notification should be assigned to a channel otherwise it will not appear. A channel allows to group notifications. User can manage settings of specific notification channel instead of managing all notifications individually.

First we need to construct a NotificationChannel object with a unique channel ID, a name, and an importance level. After that notification channel should be created using the method createNotificationChannel(). This method can be called multiple times with the same channel ID used previously, channel will not be created again.

A notification can be build using Notification.Builder. The method notify() allows to display a notification. This method requires the notification ID. It can be used later if you want to update or remove the notification.

package com.example.app

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity()
{
    private val channelId: String = "my_channel"
    private lateinit var notifManager: NotificationManager

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        createNotificationChannel()
        showNotification()
    }

    private fun createNotificationChannel()
    {
        val channelName = "Custom notification channel"
        val importance = NotificationManager.IMPORTANCE_HIGH

        val notifChannel = NotificationChannel(channelId, channelName, importance)

        notifManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notifManager.createNotificationChannel(notifChannel)
    }

    private fun showNotification()
    {
        val notificationId = 1

        val builder = Notification.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("Notification title")
            .setContentText("Notification text")

        notifManager.notify(notificationId, builder.build())
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *