
In this article, we’ll learn how to post notifications in Android with the help of an example.
Prerequisites:
In Android, we can post notifications in 4 simple steps:
- Create Notification Channel – A channel helps us to group similar notifications. From Android 8, we must create at least one channel.
- Create a Notification Builder – The Builder object provides methods to customize the individual notifications.
- Get the Permission – From Android 13, we should get the notification permission from the users.
- 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.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
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 {
createNotificationChannel()
}
fun postNotification() {
val notificationBuilder = getNotificationBuilder()
// set the title and body text
notificationBuilder.setContentTitle("Notification Title")
notificationBuilder.setContentText("Notification Message")
// post the notification
notificationManager.notify(exampleNotificationID, notificationBuilder.build())
}
private fun getNotificationBuilder(): NotificationCompat.Builder {
// this intent opens the MainActivity when the user taps on the notification
val intentNotification = Intent(context, MainActivity::class.java)
val pendingIntentNotification = PendingIntent.getActivity(
context,
exampleNotificationID,
intentNotification,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(context.applicationContext, exampleChannelID)
.setSmallIcon(R.drawable.chair)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(false)
.setStyle(NotificationCompat.BigTextStyle())
.setOnlyAlertOnce(true)
.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.enableVibration(true)
exampleChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
// Register the channel with the system.
// You can't change the importance or other notification behaviors after this.
notificationManager.createNotificationChannel(exampleChannel)
}
}
}
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()
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.
getNotificationBuilder():
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.
postNotification():
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:
notificationManager.notify(exampleNotificationID, notificationBuilder.build())
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 ...>
...
</application>
</manifest>
Next, we should ask for permission. This is similar to asking for any other permission.
import android.content.pm.PackageManager
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.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
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?) {
super.onCreate(savedInstanceState)
setContent {
YourProjectNameTheme {
val context = LocalContext.current
myNotifications = MyNotifications(context)
var permissionGranted by remember {
mutableStateOf(isPermissionGranted())
}
val permissionLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) { permissionGranted_ ->
// this is called when the user selects allow or deny
permissionGranted = permissionGranted_
}
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (permissionGranted) {
Button(
onClick = {
myNotifications.postNotification()
}
) {
Text(text = "Show Notification")
}
} else {
Button(
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) {
permissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
}
}
) {
Text(text = "Enable Permission")
}
}
}
}
}
}
}
private fun isPermissionGranted(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
} else {
true
}
}
}
Run the project. In Android 13, the output looks like this:

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

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:
References: