Notifications in Android with Example
Last Updated : 11 Feb, 2025
Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android's UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user about a process that was initiated in the application either by the user or the system. This article could help someone who's trying hard to create a notification for developmental purposes.
Notifications could be of various formats and designs depending upon the developer. In General, one must have witnessed these four types of notifications:
- Status Bar Notification (appears in the same layout as the current time, and battery percentage)
- Notification drawer Notification (appears in the drop-down menu)
- Heads-Up Notification (appears on the overlay screen, ex: WhatsApp notification, OTP messages)
- Lock-Screen Notification (I guess you know it)
In this article, we will be discussing how to produce notifications in both Java and Kotlin.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Note that select Java/Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. In this step, we are going to design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the Kotlin file. Below is the code for the activity_main.xml file.
activity_main.xml:
XML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" tools:context=".MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Send Notification" android:backgroundTint="@color/green" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Design UI:
Step 3: Create a new empty activity
Reference article:How to Create Constructor, Getter/Setter Methods and New Activity in Android Studio using Shortcuts?
Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in our app that is the user will be redirected to this page. Below is the code for the activity_after_notification.xml file.
activity_after_notification.xml:
XML <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="@color/white" tools:context=".AfterNotification"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome To GeeksforGeeks" android:textSize="15sp" android:textStyle="bold" /> </LinearLayout>
Note: Without configuring Notification Channels, you cannot build notification for applications with Android API >=26. For them generating a notification channel is mandatory. Apps with API<26 don't need notification channels they just need notification builder. Each channel is supposed to have a particular behavior that will be applicable to all the notifications which are a part of it. Every channel will, therefore, have a Channel ID which basically will act as a unique identifier for this Channel which will be useful if the user wants to differentiate a particular notification channel. In contrast, the Notification builder provides a convenient way to set the various fields of a Notification and generate content views using the platform's notification layout template but is not able to target a particular notification channel.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity File:
MainActivity.java package org.geeksforgeeks.demo; import android.Manifest; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.widget.Button; import android.widget.RemoteViews; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; public class MainActivity extends AppCompatActivity { private final String channelId = "i.apps.notifications"; // Unique channel ID for notifications private final String description = "Test notification"; // Description for the notification channel private final int notificationId = 1234; // Unique identifier for the notification @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = findViewById(R.id.btn); // Create a notification channel (required for Android 8.0 and higher) createNotificationChannel(); btn.setOnClickListener(v -> { // Request runtime permission for notifications on Android 13 and higher if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, 101 ); return; } } sendNotification(); // Trigger the notification }); } /** * Create a notification channel for devices running Android 8.0 or higher. * A channel groups notifications with similar behavior. */ private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel( channelId, description, NotificationManager.IMPORTANCE_HIGH ); notificationChannel.enableLights(true); // Turn on notification light notificationChannel.setLightColor(Color.GREEN); notificationChannel.enableVibration(true); // Allow vibration for notifications NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) { notificationManager.createNotificationChannel(notificationChannel); } } } /** * Build and send a notification with a custom layout and action. */ @SuppressLint("MissingPermission") private void sendNotification() { // Intent that triggers when the notification is tapped Intent intent = new Intent(this, AfterNotification.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); // Custom layout for the notification content RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.activity_after_notification); // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.gfg_logo) // Notification icon .setContent(contentView) // Custom notification content .setContentTitle("Hello") // Title displayed in the notification .setContentText("Welcome to GeeksforGeeks!!") // Text displayed in the notification .setContentIntent(pendingIntent) // Pending intent triggered when tapped .setAutoCancel(true) // Dismiss notification when tapped .setPriority(NotificationCompat.PRIORITY_HIGH); // Notification priority for better visibility // Display the notification NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, builder.build()); } }
MainActivity.kt package org.geeksforgeeks.demo import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.os.Build import android.os.Bundle import android.widget.Button import android.widget.RemoteViews import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat class MainActivity : AppCompatActivity() { private val channelId = "i.apps.notifications" // Unique channel ID for notifications private val description = "Test notification" // Description for the notification channel private val notificationId = 1234 // Unique identifier for the notification override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btn = findViewById<Button>(R.id.btn) // Create a notification channel (required for Android 8.0 and higher) createNotificationChannel() btn.setOnClickListener { // Request runtime permission for notifications on Android 13 and higher if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 101 ) return@setOnClickListener } } sendNotification() // Trigger the notification } } /** * Create a notification channel for devices running Android 8.0 or higher. * A channel groups notifications with similar behavior. */ private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( channelId, description, NotificationManager.IMPORTANCE_HIGH ).apply { enableLights(true) // Turn on notification light lightColor = Color.GREEN enableVibration(true) // Allow vibration for notifications } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(notificationChannel) } } /** * Build and send a notification with a custom layout and action. */ @SuppressLint("MissingPermission") private fun sendNotification() { // Intent that triggers when the notification is tapped val intent = Intent(this, AfterNotification::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) // Custom layout for the notification content val contentView = RemoteViews(packageName, R.layout.activity_after_notification) // Build the notification val builder = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.gfg_logo) // Notification icon .setContent(contentView) // Custom notification content .setContentTitle("Hello") // Title displayed in the notification .setContentText("Welcome to GeeksforGeeks!!") // Text displayed in the notification .setContentIntent(pendingIntent) // Pending intent triggered when tapped .setAutoCancel(true) // Dismiss notification when tapped .setPriority(NotificationCompat.PRIORITY_HIGH) // Notification priority for better visibility // Display the notification with(NotificationManagerCompat.from(this)) { notify(notificationId, builder.build()) } } }
With this, we have now successfully created a "Notification" for our application. Note that the parameters listed in the above code are required and the absence of any single parameter could result in crashing or not starting the application. The content title, content text, small icon are customizable parameters but are mandatory also. One can change their values according to the requirement.
Output:
For learning more about the topic refer to these articles:
Similar Reads
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
TextView
TextView in KotlinAndroid TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio. Following steps are used to create Steps to Implement TextViewSteps by Step implementation for creating an application wh
3 min read
Dynamic TextView in KotlinAndroid TextView is an user interface that is used to display some text to the user. In this article we will be discussing how to programmatically create a TextView in Kotlin . Step by Step ImplementationStep 1: Create a new projectLetâs start by first creating a project in Android Studio. To do so,
2 min read
AutoCompleteTextView in KotlinAndroid AutoCompleteTextView is an advanced EditText which shows a list of suggestions when user starts typing text. When the user starts typing, a drop-down menu appears, showing a list of relevant suggestions based on the user input. The user can then select an item from the list.The AutoCompleteT
3 min read
Dynamic AutoCompleteTextView in KotlinAndroid AutoCompleteTextView is an advanced EditText which shows a list of suggestions when user starts typing text. When the user starts typing, a drop-down menu appears, showing a list of relevant suggestions based on the user input. The user can then select an item from the list.The AutoCompleteT
4 min read
CheckedTextView in KotlinCheckedTextView is an extension of TextView in Android that includes a checkmark, making it function like a checkbox. It is commonly used in list views where items can be selected or toggled between checked and unchecked states. Users can tap the text to change its checked status, and the checkmark
2 min read
Dynamic CheckedTextView in KotlinCheckedTextView is an extension of TextView in Android that includes a checkmark, making it function like a checkbox. It is commonly used in list views where items can be selected or toggled between checked and unchecked states. Users can tap the text to change its checked status, and the checkmark
2 min read
ScrollView
ImageView
ListView
Button
Button in AndroidIn Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.Class Hierarchy of the Button Class in Kotlinkotlin.
3 min read
ImageButton in KotlinAndroid ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton, et
3 min read
Dynamic ImageButton in KotlinAn ImageButton in Android is a specialized Button that displays an image instead of text while functioning like a regular button. When clicked, it triggers an action just like a standard button. Android provides various button types, including ImageButton, ToggleButton, and more. To set an image on
2 min read
RadioButton in KotlinAndroid Radio Button is bi-state button which can either be checked or unchecked. Also, it's working is same as Checkbox except that radio button can not allow to be unchecked once it was selected. Generally, we use RadioButton controls to allow users to select one option from multiple options. By d
4 min read
Dynamic RadioButton in KotlinAn Android RadioButton is a bi-state button that can be either checked or unchecked. It functions similarly to a CheckBox, but with one key difference: once selected, a RadioButton cannot be unchecked by tapping it again. RadioButtons are typically used within a RadioGroup to allow users to select o
2 min read
EditText
Layouts
Bar
SeekBar in KotlinSeekBar in Android is a modified version of progressBar that has a draggable thumb in which a user can drag the thumb back and forth to set the current progress value. We can use SeekBar in our Android Devices like Brightness control, volume control etc. It is one of the important user interface ele
3 min read
Dynamic SeekBar in KotlinSeekBar in Android is a modified version of progressBar that has a draggable thumb in which a user can drag the thumb back and forth to set the current progress value. We can use SeekBar in our Android Devices like Brightness control, volume control etc. It is one of the important user interface ele
2 min read
Discrete SeekBar in KotlinIn Android Discrete SeekBar is just an advancement of progressBar just like the SeekBar, the only difference in SeekBar and discrete SeekBar being that in discrete SeekBar, we can only set the value only to discrete values like 1, 2, 3, and so on. In this article, we will be discussing how to create
2 min read
RatingBar in KotlinAndroid RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars. In RatingBar, we can set the step size using android:stepSiz
3 min read
Dynamic RatingBar in KotlinAndroid RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and Progress Bar that shows star ratings and it allow users to give the rating by clicking on the stars.In RatingBar, we can set the step size using android:stepSiz
3 min read
ProgressBar in KotlinAndroid ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the progress bar to estimate the time remaining in operation. There are two modes of ProgressBarDeterminate ProgressBarIndetermina
3 min read
Dynamic ProgressBar in KotlinAndroid ProgressBar is user interface control that is used to show some kind of progress. For instance, loading of some page, downloading of some file or waiting for some event to complete. In this article we will be discussing how to programmatically create a progress bar in Kotlin.Step by Step Imp
2 min read
Switcher