Creating notifications on Android
06 Sep 2018A notification is a message that is shown outside of an application window by the android system to inform the user about information like communication from other people, reminders and other timely information.
Code for the this tutorial is available on my GitHub.
Notification layout
The most common parts of a notification are indicated in figure above as follows:
- Small icon: This is required and set with
setSmallIcon()
. - App name: This is provided by the system.
- Time stamp: This is provided by the system but you can override with
setWhen()
or hide it withsetShowWhen(false)
. - Large icon: This is optional (usually used only for contact photos; do not use it for your app icon) and set with
setLargeIcon()
. - Title: This is optional and set with
setContentTitle()
. - Text: This is optional and set with
setContentText()
.
Creating a notification
Creating a basic notification for Android is pretty simple. The first step is to get the notification manger service which is the system service that handles notifications.
Notification manager service
Get the notification manager system service.
Notification channels
To show a notification in Android Oreo and above we need to create a notification channel. A user can disable or fine tune the visual and auditory options for each channel separately.
Setting the importance to IMPORTANCE_HIGH
will make the notification pop up as a Heads-up notification
.
Load Bitmap image for Large Icon
We can also include a large icon in the notification, but it needs to be of type Bitmap.
Create a pending Intent
Here we create a PendingIntent
that is used by the notification manger to launch the app when the notification is clicked.
Build the notification
Next we will create the notification using the NotificationCompat.Builder
and set the notification’s content and channel.
setAutoCancel(true)
will dismiss the notification when user clicks on it.
Set notification priority
We had already set the priority as high when we created the notification channel. But notification channels are not supported
by devices running Nougat and below. So for these devices we need to set the priority using the setPriority()
method.
Show the notification
The last step is to call the notify method and pass in unique id and the result of
NotificationCompat.Builder.build()
.
Now when the app opens, a notification should popup like above.
More info about creating Android notifications can be found at developer.android.com.