How to Post Notifications in Android?

Android Post Notifications

In this article, we’ll learn how to post notifications in Android with the help of an example.


In Android, we can post notifications in 4 simple steps:

  1. Create Notification Channel – A channel helps us to group similar notifications. From Android 8, we must create at least one channel.
  2. Create a Notification Builder – The Builder object provides methods to customize the individual notifications.
  3. Get the Permission – From Android 13, we should get the notification permission from the users.
  4. Post the Notification – Once we get the permission, we can post notifications.

Let’s start coding. It is a good practice to keep all the notification-related methods in one class. So, create a MyNotifications class and add the following code:

import android.content.Context
import android.content.Intent
import android.os.Build

class MyNotifications(private val context: Context) {

    private val notificationManager =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    private val exampleChannelID = "EXAMPLE_CHANNEL"
    private val exampleNotificationID = 1

    init {

    fun postNotification() {
        val notificationBuilder = getNotificationBuilder()

        // set the title and body text
        notificationBuilder.setContentTitle("Notification Title")
        notificationBuilder.setContentText("Notification Message")

        // post the notification

    private fun getNotificationBuilder(): NotificationCompat.Builder {
        // this intent opens the MainActivity when the user taps on the notification
        val intentNotification = Intent(context,
        val pendingIntentNotification = PendingIntent.getActivity(
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT

        val builder = NotificationCompat.Builder(context.applicationContext, exampleChannelID)     
            .setDefaults(NotificationCompat.DEFAULT_ALL) // For backward compatibility
            .setPriority(NotificationManager.IMPORTANCE_HIGH) // for backward compatibility

        return builder

    private fun createNotificationChannel() {
        // check the Android 8.0 (API level 26) version
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Channel name"
            val descriptionText = "Channel description"
            val importance = NotificationManager.IMPORTANCE_HIGH

            val exampleChannel = NotificationChannel(exampleChannelID, name, importance)
            exampleChannel.description = descriptionText
            exampleChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

            // Register the channel with the system.
            // You can't change the importance or other notification behaviors after this.

Let’s understand the code.

First, we created a notificationManager object.

private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager    

It contains methods for creating a channel and posting the notification.

There are two constant values representing the IDs.

private val exampleChannelID = "EXAMPLE_CHANNEL"    
private val exampleNotificationID = 1

Every channel and notification must have a unique ID. Channel IDs must be strings, while notification IDs must be integers.

Next, there are three methods in the class:

  • postNotification()
  • getNotificationBuilder()
  • createNotificationChannel()


It creates a new channel. A channel is a group of notifications. It allows you to customize their appearance and behavior.

We created the channel using the following code:

val exampleChannel = NotificationChannel(exampleChannelID, name, importance)     

There are three parameters:

  • Channel ID – Unique id for each channel.
  • name – Name of the channel.
  • importance- Importance level for all the notifications posted to this channel.

It provides various methods for customizing the notifications. Some of them are:

  • setDescription() – Sets the user-visible description of this channel. The recommended maximum length is 300 characters; the value may be truncated if it is too long.
  • enableVibration() – Sets whether notification should vibrate.
  • lockscreenVisibility() – If the notifications should appear on the lock screen or not.

You can find all the methods in the official docs.

The method is called from the init block, which means it gets executed every time we create the object of MyNotifications. It is safe to do this as the Android system ignores the code if the channel already exists.


The Builder object allows you to set the individual properties (like tile, message, icon, etc. ) of a notification.

val builder = NotificationCompat.Builder(context.applicationContext, exampleChannelID)     

The Builder() class takes context and channel ID. Channel ID is the ID of the channel to which this notification is posted.

We can call different methods to customize the notification.

  • setSmallIcon() – App icon. It is required.
  • setContentIntent() – The intent that should be sent when we tap on this notification. In the above code, the intent opens the MainActivity.
  • setAutoCancel() – If the notification should be canceled when we tap on it.
  • setStyle() – Text style for the message.
  • setOnlyAlertOnce() – It makes the sound if the notification is not showing already.
  • setDefaults() – It sets the default settings for backward compatibility.
  • setPriority() – Sets the priority for backward compatibility.

You can find all the methods of the Builder class here.


First, we have set the title and description:

notificationBuilder.setContentTitle("Notification Title")
notificationBuilder.setContentText("Notification Message")    

Next, to post the notification, call the notify() method:


Get the Notification Permission:

Starting from Android 13 (API level 33), we should get the POST_NOTIFICATIONS permission from the user. Otherwise, our notifications won’t work.

First, declare the following permission in the manifest file:

<manifest ...>

    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>    

    <application ...>


Next, we should ask for permission. This is similar to asking for any other permission.

import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat

class MainActivity : ComponentActivity() {

    private lateinit var myNotifications: MyNotifications

    override fun onCreate(savedInstanceState: Bundle?) {
        setContent {
            YourProjectNameTheme {
                val context = LocalContext.current
                myNotifications = MyNotifications(context)

                var permissionGranted by remember {

                val permissionLauncher =
                    rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) { permissionGranted_ ->     
                        // this is called when the user selects allow or deny
                        permissionGranted = permissionGranted_

                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                        modifier = Modifier
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        if (permissionGranted) {
                                onClick = {
                            ) {
                                Text(text = "Show Notification")
                        } else {
                                onClick = {
                                    // ask for permission
                                    // isPermissionGranted() returns true if the device is running 12 and below
                                    // I added this condition to remove the warning
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                            ) {
                                Text(text = "Enable Permission")

    private fun isPermissionGranted(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ) == PackageManager.PERMISSION_GRANTED
        } else {

Run the project. In Android 13, the output looks like this:

Post Notifications Android

Open the app settings and click on the Notifications option. You will find our channel.

Notification Channels

This is how we post notifications in Android. I hope you have learned something new. If you have any doubts, leave a comment below.

Related Articles:


Leave a Comment