Android Notifications from Notification Manager Tutorial with Example

Introduction to Notifications

Android provides an ability to the applications to engage its users whether they are using the application or not. Android Notifications are simple notifications from the application which is displayed outside the application. This type of notification can be easily displayed with the help of NotificationManager class. You have seen a lot of times when some download starts and completes or something installed successfully, Android system notifies the user about the action.

Displaying Simple Android Notifications

NotificationManager

You can use NotificationManager class by simply instantiating it with the getSystemService() method. getSystemService() method request the Android system to use Android notifications service.

PendingIntent

PendingIntent is the activity that is displayed when the user clicks on the Android notification. It can be another 3rd Party application or the same application. You must specify the context and intent to call on notification click.

Notification

To create a notification you must instantiate Notification class with Notification.Builder(context) and pass icon, title, and PendingIntent as the parameters of the Notification. This will help the Notification class to display the notification with some icon at some specific time. Most of the applications display the notification when some important event occurs.

1

2

3

4

5

6

Notification notification=newNotification.Builder(this)

.setContentTitle(title)

.setContentText(subject+": "+body)

.setSmallIcon(R.drawable.icon)

.setContentIntent(pending)

.setAutoCancel(true).build();

Now the important part for displaying the Android notifications is to call the notify method of NotificationManager class to display the notification.

With NotificationCompact you can add the number of notification when a new notification arrives.

1

builder.setNumber(++numMessages);

Creating an Expandable Notification

After the launch of Android 4.1, the notifications support also changed from simple notifications to the expandable notification. When there is a bundle of notifications Android 4.1 shows an expandable notification with lesser text. Or when another notification comes after expandable notification, the expandable notification contracts itself and expands on swipe on the notification.

to create an expandable notification you must add NotificationCompat.InboxStyle to the notification. Also, add the title for expanded notification and the lines to be displayed i.e. the Text of the Notification.