Create and Display Notification on Android with Example

Spread knowledge

Displaying notification is one of the most important features in an Android app. Notification are short messages which appear on home screen of the device. In this example you will learn how to programatically create and display a Notification from your app which will work for all versions of Android (Even Oreo)

notification_image

Notification Channel

Before beginning with displaying notifications it is important to understand what notification channels are.

From version 8.0 (Oreo) Android has started grouping notifications into channels. Each channel is supposed to have a particular behavior which 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.

The important thing to note is the concept of Channels is not applicable to pre Oreo Android devices. Which means that Notification Channels should neither be created nor will they work on any devices before Oreo

Following code snippet shows how to create a Notification Channel

// This is the Notification Channel ID. More about this in the next section
public static final String NOTIFICATION_CHANNEL_ID = "channel_id";

//User visible Channel Name
public static final String CHANNEL_NAME = "Notification Channel";

// Importance applicable to all the notifications in this Channel
int importance = NotificationManager.IMPORTANCE_DEFAULT;

//Notification channel should only be created for devices running Android 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, CHANNEL_NAME, importance);

    //Boolean value to set if lights are enabled for Notifications from this Channel
    notificationChannel.enableLights(true);

    //Boolean value to set if vibration are enabled for Notifications from this Channel
    notificationChannel.enableVibration(true);

    //Sets the color of Notification Light
    notificationChannel.setLightColor(Color.GREEN);

    //Set the vibration pattern for notifications. Pattern is in milliseconds with the format {delay,play,sleep,play,sleep...}
    notificationChannel.setVibrationPattern(new long[] {
        500,
        500,
        500,
        500,
        500
    });

    //Sets whether notifications from these Channel should be visible on Lockscreen or not
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
}

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);

 

You can read more about Notification Channels here

Displaying a Simple Notification:

Before implementing it is important to understand what are various components in a Notification design (later we can check how to implement each of them)

Below is the latest default design of an Android Notification . You can only define content of various components in the design( You cannot change the UI design itself as it defined by system templates)

notification_design
Courtesy: Google Dev
  1. Small Icon
  2. App Name (Given by System)
  3. Timestamp
  4. Large Icon
  5. Content Title
  6. Content Text

We will be using NotificationCompat.Builder class to display the notification as this is what will give us access to latest features and yet be compatible on versions as old Android 4.0

Creating a Notification

Notification.Builder is the best way to create a Notification object. You can define all the components of Notification mentioned above by calling setters on the builder object as shown in the code snippet below. You can note that we pass a string as parameter to the Notification.Builder constructor, this string is the Notification Channel ID which means that this notification will now be a part of that particular channel on post Oreo devices. On pre-Oreo devices this parameter is ignored.

// This is the Notification Channel ID. More about this in the next section
public static final String NOTIFICATION_CHANNEL_ID = "channel_id";

//Notification Channel ID passed as a parameter here will be ignored for all the Android versions below 8.0
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

builder.setContentTitle("This is heading");
builder.setContentText("This is description");
builder.setSmallIcon(R.drawable.icon);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon));

Notification notification = builder.build();

 

Issuing the Notification

Merely creating a notification object wont display it, to display the  notification you will need to call notify() on the NotificationManager object as shown below. As you can see a unique integer identifier is also required while issuing the notification. This integer acts as a unique identifier for that particular notification

// Unique identifier for notification
public static final int NOTIFICATION_ID = 101;

//This is what will will issue the notification i.e.notification will be visible
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(NOTIFICATION_ID, notification);

Set Priority

Notification is basically a reminder to user. Some notifications might be so important that the user needs to be immediately alerted while others might have a low importance and could be hidden from some places. To facilitate this Android allows developers to set the priority of a notification while creating it.

notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);

/*
PRIORITY_MIN : Lowest Priority. These notifications might not be shown to user unless under special circumstances

PRIORITY_LOW : Lower Priority. The UI may choose to show these items smaller, or at a different position in the list, compared with your app's PRIORITY_DEFAULT items.

PRIORITY_DEFAULT : Default priority.

PRIORITY_HIGH : Higher Priority. The UI may choose to show these items larger, or at a different position in notification lists, compared with your app's PRIORITY_DEFAULT items.

PRIORITY_MAX : Highest Priority. User is very likely to be immediately notified of this

*/

 

Setting priority with this API doesn’t guarantee that Android UI will honor the same priority. The system decides on the Notification priority based on a number of factors including this API. The behavior might be different on different platforms

Setting Sound Alert:

We can set a sound which will play as soon as the Notification is triggered. Notifications with sound are most likely to be considered of high importance by Android UI.

/*
setSound() takes in a Uri as the paramater. In this example I am using predefined Alarm Uri from Ringtone.
You can set any custom sound by just providing the Uri

*/
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));

 

Setting Vibration Pattern:

With the following you can set the vibration pattern which will be played when the Notification appears

/*
setVibrate takes in a long array which represents the vibrate pattern.
Its a {delay,vibrate,sleep,vibrate,sleep.....} pattern. The values are to be entered in milliseconds
*/
notificationBuilder.setVibrate(new long[] {
    500,
    500,
    500,
    500
});

 

Lock Screen Visibility

Based on your requirement you might or might not want the user to view your notification on lock screen. This can be simply be implemented with the following

notificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

/*

VISIBILITY_PUBLIC shows the notification's full content.

VISIBILITY_SECRET doesn't show any part of this notification on the lock screen.

VISIBILITY_PRIVATE shows basic information, such as the notification's icon and the content title, but hides the notification's full content.

*/

 

Setting Content Intent:

Notifications respond to a tap. You can open the corresponding activity when the notification is tapped. This can be implemented with the help of an Pending Intent as shown below.

In the following code we will open a Activity by the name MainActivity when the notification is tapped

//This intent will be fired when the notification is tapped
Intent intent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 1001, intent, 0);

//Following will set the tap action
notificationBuilder.setContentIntent(pendingIntent);

 

Action Buttons for your notification

Apart from responding to the tap action from the user, Notifications even have the capability of adding upto three buttons known as Action Buttons.action_notification

Action Buttons enable user to respond quickly. Setting these is as simple as setting the default tap action to your notification. In the following code snippet we add action button which will not open a activity but only trigger a BroadcastReceiver which performs its operation in background thereby not interrupting the user.

Intent intent = new Intent(this, MyReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1002, intent, PendingIntent.FLAG_UPDATE_CURRENT);

builder.addAction(R.drawable.icon, getResources().getString(R.string.app_name), pendingIntent);

/*
addAction taken in three parameters

1st Param Icon

2nd Param Title for the Action Button

3rd Param Pending Intent

*/

 

Custom Design

You must have seen many custom notifications with either multiple lines in the content or a big content image which is visible when the user expands the notification. In this section we will learn how to implement these

This kind of notifications can be implemented with help of setStyle(Notification.Style) API on the Notification builder object.  Notification.Style class has the following subclasses each one of which define a particular style and can be passed in as a paramater to setStyle().

  • NotificationCompat.BigTextStyle

    This style is used to display text in the expanded content area. This text is visible only when the user scrolls down to expand the notification

    Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setContentTitle("This is the title")
        .setContentText("This is the subtext")
        .setSmallIcon(R.drawable.icon)
        .setStyle(new NotificationCompat.BigTextStyle()
            .bigText("This is the expandable content text"))
        .build();

     

  • NotificationCompat.InboxStyle

    This style should be used if instead of one continuous line of text you want to add multiple short summary lines. One good example of this is the gmail notification for multiple new mails in our inbox.

     

    Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setContentTitle("This is the title")
        .setContentText("This is the subtext")
        .setSmallIcon(R.drawable.icon)
        .setStyle(new NotificationCompat.InboxStyle()
            .addLine("This is the first line")
            .addLine("This is the second line")
            .addLine("This is the third line"))
        .build();

     

  • NotificationCompat.BigPictureStyle

    Instead of text you can even add an image to the expanded view of the notification. When in collapsed mode user sees small and large icon, only when expanded this image is also visible.

     

    Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setContentTitle("This is the Title")
        .setContentText("This is the sub text")
        .setSmallIcon(R.drawable.icon)
        .setStyle(new NotificationCompat.BigPictureStyle()
            .bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.icon)))
        .build();

     

    If the platform doesn’t support large image notification, this has no effect and only the normal notification is visible

Remember how we pass a unique integer id while issuing every notification using the notify() API. That is actually the notification id which is supposed to be unique and can be used to reference that notification later. Now you will know how it helps.

Updating a Notification

In order to update the notification you need to call notify() with the same notification id again. If the notification is already dismissed a new one is created.

Removing a Notification

Much similar to how we use the notification id to update the notification you can use it to cancel a notification progamatically. Just pass the reference of the notification id you want to cancel as shown below

notificationManagerCompat.cancel(NOTIFICATION_ID);

 


Spread knowledge

1 Reply to “Create and Display Notification on Android with Example”

Leave a Reply

Your email address will not be published. Required fields are marked *