Creating a simple android notification with example

Android notification offers a short timely information about the app to the users. A simple android notification is made up of title, description and an icon. We can add interaction to android notification when user taps on it we launch an activity.

The video below illustrate How to show android notification which has tap action listener.

By default, android notification are set to fit on one line, if you want your notification to be longer you must setStyle using setStyle() method.

android notification with large image

In this tutorial we are going to create a simple android notification with on tap listener.

To get started first we will add library dependency.

Adding support library

Android notification requires support library. Open your module-level

Include the following support library if it doesn’t exist.

Creating android notification

We are going to create a simple android notification that has a title, text and an icon.

Other component we have added is

setPriority() this determines how intrusive notification should be and setAutoCancel(true) which automatically when the user taps it.

Displaying android notification

Once you have created you notification, now it’s time to make it appear call

and pass UniqueId and result of 

Save the unique id for later update or cancellation of a this notification.

Our final code for android notification.

To display your android notification, call the above method.

Android notification on Tap Action

Android notifications should respond to tap, Let’s tap action to our notification when a user taps on the notification a new activity will be launched.
Adding on tap listener to our notification, You will need to specify Notification Content Intent via Pending Intent Object and pass it to setContentIntent()

Call the method above to display android notification which has on tap listener.

Note 1: NotificationActivity is the activity that is going to show when notification is tapped.

Note 2: Starting from android 8 and higher you need to register your app’s notification channel with the system before posting your notification.

This is done by passing an instance of notificationChannel to createNotificationChannel().

create notification channel for android 8 and above

If you are dealing with android 8 and higher call this method when app starts. No had including it in android version 8 and below.

For additional help or clarification, kindly comment below.
To access the project source, use the github link below.