How to Push Notification in Android?

21 Dec, 2020
Notification is a message which appears outside of our Application’s normal UI. A notification can appear in different formats and locations such as an icon in the status bar, a more detailed entry in the notification drawer, etc. Through the notification, we can notify users about any important updates, events of our application. By clicking the notification user can open any activity of our application or can do some action like opening any webpage etc. 
Let see the basic design of a notification template that appears in the navigation drawer. 
Part of a Notification 
Method for defining contents 
Type of argument needs to pass into the method
We shall discuss all the concepts mentioned below step by step,
Creating a basic notificationCreating notification channelAdding large iconMaking notification expandableMaking notification clickableAdding an action button to our notification
Creating a basic notification
Creating notification channel
Adding large icon
Making notification expandable
Making notification clickable
Adding an action button to our notification
To create a basic notification at first we need to build a notification. Now to build notification, we must use NotificationCompat.Builder() class where we need to pass a context of activity and a channel id as an argument while making an instance of the class. Please note here we are not using Notification.Builder(). NotificationCompat gives compatibility to upper versions (Android 8.0 and above) with lower versions (below Android 8.0).
Kotlin
val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID)                    .setContentTitle(et1.text.toString())                    .setContentText(et2.text.toString())                    .setSmallIcon(R.drawable.spp_notification_foreground)                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                    .build()
Please note, here we need to set the priority of the notification accordingly by the setPriority() method.
Now to deliver the notification we need an object of NotificationManagerCompat class and then we notify it.
Kotlin
val nManager = NotificationManagerCompat.from(this)// Here we need to set an unique id for each// notification and the notification Builder            nManager.notify(1, nBuilder)
Please note that, in this method, we can deliver notification only in the android versions below 8.0 but in the android versions 8.0 and upper, no notification will appear by only this block of code.
Now to deliver notifications on android version 8.0 and above versions, we need to create a notification channel. This  Notification Channel concept comes from android 8.0. Here every application may have multiple channels for different types of notifications and each channel has some type of notification. Before you can deliver the notification on Android 8.0 and above versions, you must register your app’s notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel().
Kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply {                description = CHANNEL_DESCRIPTION            }            val nManager: NotificationManager =            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager            nManager.createNotificationChannel(channel)        }
Please note that here we must provide a unique CHANNEL_ID for each channel and also we must give a CHANNEL_NAME and CHANNEL_DESCRIPTION. Also, we must give channel importance.
To set a large icon we use the setLargeIcon() method which is applied to the instance of the NotificationCompat.Builder() class. In this method, we need to pass a Bitmap form of an image. Now to convert an image file (e.g. jpg, jpeg, png, etc.)  of the drawable folder into a Bitmap, we use the following code in Kotlin
Kotlin
// converting a jpeg file to Bitmap file and making an instance of Bitmap!val imgBitmap=BitmapFactory.decodeResource(resources,R.drawable.gfg_green)  // Building notificationval nBuilder= NotificationCompat.Builder(this,CHANNEL_ID)                    .setContentTitle(et1.text.toString())                    .setContentText(et2.text.toString())                    .setSmallIcon(R.drawable.spp_notification_foreground)                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                    // passing the Bitmap object as an argument                     .setLargeIcon(imgBitmap)                    .build()
In the short template of the notification, large information can’t be shown. Therefore we need  to make the notification expandable like this:
to make such an expandable notification we use the setStyle() method on the notification builder (nBuilder) object. In this expanded area we can display an image, any text, different messages, etc. In our Application, we have added an image by passing the instance of the  NotificationCompat.BigPictureStyle class to setStyle() method.
Kotlin
val imgBitmap = BitmapFactory.decodeResource(resources,R.drawable.gfg_green)val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID)                    .setContentTitle(et1.text.toString())                    .setContentText(et2.text.toString())                    .setSmallIcon(R.drawable.spp_notification_foreground)                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                    .setLargeIcon(imgBitmap)                    // Expandable notification                    .setStyle(NotificationCompat.BigPictureStyle()                            .bigPicture(imgBitmap)                            // as we pass null in bigLargeIcon() so the large icon                             // will goes away when the notification will be expanded.                            .bigLargeIcon(null))                    .build()
We need to make our notification clickable to perform some action by clicking the notification such as open an activity or system setting or any webpage etc. Now to perform such actions intent is needed (e.g. explicit or implicit intent). In our Application, we are making an Implicit intent to open the GFG official home page.
Kotlin
// Creating the Implicit Intent to // open the home page of GFG   val intent1= Intent()        intent1.action=Intent.ACTION_VIEW        intent1.data=Uri.parse("https://www.geeksforgeeks.org/")
Now it is not necessary that whenever the notification will appear then the user will click it instantly, user can click it whenever he /she wants and therefore we also need to make an instance of PendingIntent which basically makes the intent action pending for future purpose.
Kotlin
val pendingIntent1=PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT)  // Here the four parameters are context of activity,// requestCode,Intent and flag of the pendingIntent respectively// The request code is used to trigger a// particular action in application activityval nBuilder = NotificationCompat.Builder(this,CHANNEL_ID)                    .setContentTitle(et1.text.toString())                    .setContentText(et2.text.toString())                    .setSmallIcon(R.drawable.notifications)                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                    .setLargeIcon(imgBitmap)                    .setStyle(NotificationCompat.BigPictureStyle()                            .bigPicture(imgBitmap)                            .bigLargeIcon(null))                    // here we are passing the pending intent                     .setContentIntent(pendingIntent1)                    // as we set auto cancel true, the notification                     // will disappear after afret clicking it                    .setAutoCancel(true)                    .build()
Sometimes there exists some action button at our notification template that is used to perform some action.
Here we also need an Intent and a PendingIntent. Then we need to pass the instance of the PendingIntent to addAction() method at the time of building the notification.
Kotlin
// Creating the Implicit Intent // to open the GFG contribution page   val intent2 = Intent()        intent2.action = Intent.ACTION_VIEW        intent2.data = Uri.parse("https://www.geeksforgeeks.org/contribute/")  val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID)                    .setContentTitle(et1.text.toString())                    .setContentText(et2.text.toString())                    .setSmallIcon(R.drawable.notifications)                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                    .setLargeIcon(imgBitmap)                    .setStyle(NotificationCompat.BigPictureStyle()                            .bigPicture(imgBitmap)                            .bigLargeIcon(null))                    .setContentIntent(pendingIntent1)                    .setAutoCancel(true)                    // Here we need to pass 3 arguments which are                     // icon id, title, pendingIntent respectively                    // Here we pass 0 as icon id which means no icon                    .addAction(0,"LET CONTRIBUTE",pendingIntent2)                    .build()
Let discuss all the concepts by making an Application named GFG_PushNotification. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. 
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 Kotlin as the programming language. Choose the API level according to your choice( Here we have chosen API Level 26).
After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:
CLICK HERE
***Please note that it is optional***
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     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"    tools:context=".MainActivity">      <ImageView        android:id="@+id/imgGFG"        android:layout_width="200dp"        android:layout_height="200dp"        android:layout_centerHorizontal="true"        android:layout_marginTop="70dp"        android:src="@drawable/gfg_white" />      <!-- EditText for entering the title-->    <EditText        android:id="@+id/et1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/imgGFG"        android:layout_marginLeft="30dp"        android:layout_marginRight="30dp"        android:background="#d7ffd9"        android:hint="Enter The Title"        android:padding="10dp"        android:textSize="20sp"        android:textStyle="bold" />      <!-- EditText for entering the text-->    <EditText        android:id="@+id/et2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/et1"        android:layout_marginLeft="30dp"        android:layout_marginTop="30dp"        android:layout_marginRight="30dp"        android:background="#d7ffd9"        android:hint="Enter The Text"        android:padding="10dp"        android:textSize="20sp"        android:textStyle="bold" />      <!-- Button for sending notification-->    <Button        android:id="@+id/btn1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/et2"        android:layout_marginLeft="30dp"        android:layout_marginTop="30dp"        android:layout_marginRight="30dp"        android:background="#0F9D58"        android:text="send notification"        android:textColor="#000000"        android:textSize="20sp"        android:textStyle="bold" />  </RelativeLayout>
Step 3: Insert a vector asset into the drawable folder in the res directory
Right-click on the drawable folder → New → Vector Asset → select appropriate Clip Art → give appropriate Name and adjust Size accordingly→ Next then click on the finish button as shown in the below image.
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.
Kotlin
import android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompat  class MainActivity : AppCompatActivity() {    val CHANNEL_ID = "GFG"    val CHANNEL_NAME = "GFG ContentWriting"    val CHANNEL_DESCRIPTION = "GFG NOTIFICATION"      // the String form of link for     // opening the GFG home-page    val link1 = "https://www.geeksforgeeks.org/"      // the String form of link for opening    // the GFG contribution-page    val link2 = "https://www.geeksforgeeks.org/contribute/"    lateinit var et1: EditText    lateinit var et2: EditText    lateinit var btn1: Button    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)                 // Binding Views by their IDs        et1 = findViewById(R.id.et1)        et2 = findViewById(R.id.et2)        btn1 = findViewById(R.id.btn1)        btn1.setOnClickListener {                          // Converting the .png Image file to a Bitmap!            val imgBitmap = BitmapFactory.decodeResource(resources, R.drawable.gfg_green)                          // Making intent1 to open the GFG home page            val intent1 = gfgOpenerIntent(link1)                          // Making intent2 to open The GFG contribution page            val intent2 = gfgOpenerIntent(link2)                          // Making pendingIntent1 to open the GFG home             // page after clicking the Notification            val pendingIntent1 = PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT)                          // Making pendingIntent2 to open the GFG contribution             // page after clicking the actionButton of the notification            val pendingIntent2 = PendingIntent.getActivity(this, 6, intent2, PendingIntent.FLAG_UPDATE_CURRENT)                          // By invoking the notificationChannel() function we             // are registering our channel to the System            notificationChannel()                          // Building the notification            val nBuilder = NotificationCompat.Builder(this, CHANNEL_ID)                                          // adding notification Title                    .setContentTitle(et1.text.toString())                                          // adding notification Text                    .setContentText(et2.text.toString())                                          // adding notification SmallIcon                    .setSmallIcon(R.drawable.ic_android_black_24dp)                                          // adding notification Priority                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)                                          // making the notification clickable                    .setContentIntent(pendingIntent1)                    .setAutoCancel(true)                                          // adding action button                    .addAction(0, "LET CONTRIBUTE", pendingIntent2)                                          // adding largeIcon                    .setLargeIcon(imgBitmap)                                          // making notification Expandable                    .setStyle(NotificationCompat.BigPictureStyle()                            .bigPicture(imgBitmap)                            .bigLargeIcon(null))                    .build()            // finally notifying the notification            val nManager = NotificationManagerCompat.from(this)            nManager.notify(1, nBuilder)        }    }      // Creating the notification channel    private fun notificationChannel() {        // check if the version is equal or greater        // than android oreo version        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            // creating notification channel and setting             // the description of the channel            val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply {                description = CHANNEL_DESCRIPTION            }            // registering the channel to the System            val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager            notificationManager.createNotificationChannel(channel)        }    }      // The function gfgOpenerIntent() returns     // an Implicit Intent to open a webpage    private fun gfgOpenerIntent(link: String): Intent {        val intent = Intent()        intent.action = Intent.ACTION_VIEW        intent.data = Uri.parse(link)        return intent    }}
android
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.