Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Appearance in Android
3.
Steps in Creating Notification
3.1.
Creating Notification Channel
3.2.
Creating Notification
3.3.
Actions
3.4.
Issue Notification
4.
Example Application
5.
FAQs
5.1.
Is it possible to get directed to any app layout through notification?
5.2.
What is the use of channel Id?
5.3.
Is it possible to add a response to the notification?
6.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Notifications in Android

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this blog, we will be looking into the Notification feature of Android. Notification is a feature that gives you a little message regarding your application, so the user directly jumps on the app through that notification. If you wonder how notification is different from toast in android, then a toast is available only while the app is running and for a very few moments. But notification can occur even when using any other app and remains in the status bar until we respond to it.

In this article, we will learn how to manipulate its appearance when it first comes to the status bar and its detailed form in the notification drawer.

Appearance in Android

Notification in android first shows up on the status bar with a small icon regarding the notification.

If you want detailed information regarding the notification, we can scroll through the notification drawer.

Android Developers

You can set the different properties to the notification in the notification drawer, e.g., icon, message, title, response, etc.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Steps in Creating Notification

There are several steps in creating a notification channel and some additional steps for the system with API level 26+. We will be using NotificationCompat.Builder class this class provides lots of methods and services to get our work done, so let us first discuss the methods and Builders it offers.

S.No. Builder Method Description
1 Notification build() This method returns the notification object and combines all the objects that have been set.
2 NotificationCompat.Builder setAutoCancel (boolean autoCancel) To cancel the notification when the user clicks on it.
3 NotificationCompat.Builder setContent (RemoteViews views) This method supplies custom RemoteViews to use instead of the standard one.
4 NotificationCompat.Builder setContentInfo (CharSequence info) This method sets the large text on the right of the notification.
5 NotificationCompat.Builder setContentIntent (PendingIntent intent) Creates a pending intent when the user clicks the notification.
6 NotificationCompat.Builder setContentText (CharSequence text) Set the descriptive text in a notification.
7 NotificationCompat.Builder setContentTitle (CharSequence title) Set the title of the notification.
8 NotificationCompat.Builder setDefaults (int defaults) To set the default notification options.
9 NotificationCompat.Builder setLargeIcon (Bitmap icon) This sets an icon that is shown in the ticker and notification in a large size.
10 NotificationCompat.Builder setNumber (int number) This sets the number on the right-hand side of the notification in large size.
11 NotificationCompat.Builder setOngoing (boolean ongoing) This method sets whether this is an ongoing notification.
12 NotificationCompat.Builder setSmallIcon (int icon) This method sets the small icon to use in the notification.
13 NotificationCompat.Builder setStyle (NotificationCompat.Style style) This adds a rich notification style to be applied at build time.
14 NotificationCompat.Builder setTicker (CharSequence tickerText) This sets a text to show when the notification first arrives in the status bar.
15 NotificationCompat.Builder setVibrate (long[] pattern) Set the vibration pattern to use.
16 NotificationCompat.Builder setWhen (long when) Set the time that the event occurred. Notifications in the panel are sorted by this time.

Creating Notification Channel

Before you can issue the notification on Android 8.0 and higher, you must register your application's notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel(). So we need an if statement for checking its version SDK_INT version:

We can create a channel with the following lines of code, and you can also refer to the official site.

private void createNotificationChannel() {
   // Create the NotificationChannel, but only  for the system with API leve 26+ since
   // The NotificationChannel class is not available in the support directory
   if (Build.VERSION_CODES.O <= Build.VERSION.SDK_INT) {
       int importance = NotificationManager.IMPORTANCE_DEFAULT;
       NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
       // This registers the channel with the system; you can't change the importance
       // or other notification behaviors after this
       NotificationManager notificationManager = getSystemService(NotificationManager.class);
       notificationManager.createNotificationChannel(channel);
   }
}

Channel Id, which we have created, must be unique because that channel id is recognizing our notification. Also, this piece of code needs to execute only once.

Creating Notification

To create, you need to set the notification's content and channel using a NotificationCompat.Builder instance. Since its a builder so, there are some of its attributes:

  • Icon, set by setSmallIcon(). This sets the small icon in notification on both the notification drawer as well as the status bar.
  • Title can be set by  using setContentTitle().
  • Body text can be set by setContentText().
  • Notification’s priority, is set by setPriority().
NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this,CHANNEL_ID)
               .setSmallIcon(R.drawable.mascot_logo)
               .setContentTitle("Notifications Demo")
               .setContentText("Coding Ninjas Presents article on Notification in Android");

We do not need channel Id in the previous versions, but in Android 8.0 (API level 26) or higher, it is not being ignored.

See More, android operating system

Actions

This is regarding the action we want to attach to our notification. E.g., PendingIntent is an Intent that starts an Activity in your application. To associate the PendingIntent with a touch on the notification, call the appropriate method of NotificationCompat.Builder

Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
       PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

Now with these lines of code, when we click on the notification in the notification drawer, we will get back to our MainActivity from wherever we are.

Issue Notification

Now you can pass your notification object to the system by calling NotificationManager.notify. First, call NotificationCompat.Builder.build() method on builder object before notifying it. 

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());

Example Application

Let us consider an example applying most of the concepts we have discussed. In this example, we will make a basic notification app. When we press the notification button on the main screen, the notification is sent to us, and when we press the notification, we are redirected to the main screen again.

Step1: Start a new project in android studio with an empty activity.

Step2: Design the activity_main.xml file. Here is what I have designed for this article. I've taken coding ninjas official photo, and you can take any other image in res/drawable.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:layout_height="match_parent"
   xmlns:tools="http://schemas.android.com/tools"
   android:background="@color/teal_700"
   tools:context="MainActivity">
   

   <TextView
       android:id="@+id/tv_head"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Notification Demo"
       android:textStyle="bold"
       android:textColor="@color/black"
       android:layout_marginTop="30dp"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:textSize="30dp" />


   <ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/iv"
       android:src="@drawable/cn_logo"
       android:layout_below="@+id/tv_head"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="42dp" />


   <Button
       android:id="@+id/bt"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/iv"
       android:backgroundTint="#024C4C"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="62dp"
       android:text="Notification" />


   <TextView
       android:id="@+id/textView2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Coding Ninjas "
       android:textColor="@color/black"
       android:textSize="30dp"
       android:fontFamily="sans-serif-condensed"
       android:layout_below="@+id/bt"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="200dp" />

</RelativeLayout>


Step3: Now it's time to give some functioning to this layout, which means designing the MainActivity


package com.example.notificationdemo;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;


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 android.os.Bundle;
import android.view.View;
import android.widget.Button;



public class MainActivity extends AppCompatActivity {
   Button b1;
   String CHANNEL_ID = "channelId";
   String CHANNEL_NAME = "channelName";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       createNotificationChannel();
       b1 = (Button)findViewById(R.id.bt);
       b1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               addNotification();
           }
       });
   }
   private void addNotification() {
       NotificationCompat.Builder mybuilder =
               new NotificationCompat.Builder(this,CHANNEL_ID)
  //this icon is shown on the status bar
                       .setSmallIcon(R.drawable.mascot_logo)
                       .setContentTitle("Notifications Demo")
                       .setContentText("Coding Ninjas Presents article on Notification in Android");
       //With this intent you will be directed to the main activity again.
       Intent notificationIntent = new Intent(this, MainActivity.class);
       PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
               PendingIntent.FLAG_UPDATE_CURRENT);
       mybuilder.setContentIntent(contentIntent);


       //This line add as a notification
       NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       manager.notify(0, mybuilder.build());
   }


   private void createNotificationChannel() {
       // This create the NotificationChannel, but only on API 26+ because
       // The NotificationChannel class is new and not in the support library
       if (Build.VERSION_CODES.O <= Build.VERSION.SDK_INT) {
           int importance = NotificationManager.IMPORTANCE_DEFAULT;
           NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
           // Register the channel with the system; you can't change the importance
           // or other notification behaviors after this
           NotificationManager notificationManager = getSystemService(NotificationManager.class);
           notificationManager.createNotificationChannel(channel);
       }
   }
}


Step4: Now, compile and run the app. You will get the following as output.
 

Now press the notification button you will get a notification with a bit of sound. There appears an icon on the status bar that corresponds to your notification.

You can see a small icon just next to the time in the status bar on drawing the notification drawer, and you will get the detailed notification.

FAQs

Is it possible to get directed to any app layout through notification?

Yes, you have to pass that activity where you want to go in the pending intent.
 

What is the use of channel Id?

Channel Id is used to identify each channel id uniquely.
 

Is it possible to add a response to the notification?

Yes, there is a whole bunch of responses available like action button, reply, progress bar, etc.

Conclusion 

In this article, we have extensively discussed Notification in Android and its implementation in Android Studio. We discussed how notifications could be created and used in an android application and how to add a response to it.
We hope that this blog has helped you enrich your knowledge regarding Notification in Android. To learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow.
Happy Coding!

Previous article
Android Drag and Drop Feature
Next article
Sending Emails In Android
Live masterclass