Creating notifications on Android06 Sep 2018
A 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.
The most common parts of a notification are indicated in figure above as follows:
- Small icon: This is required and set with
- 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 with
- Large icon: This is optional (usually used only for contact photos; do not use it for your app icon) and set with
- Title: This is optional and set with
- Text: This is optional and set with
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.
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
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
Show the notification
The last step is to call the notify method and pass in unique id and the result of
Now when the app opens, a notification should popup like above.
More info about creating Android notifications can be found at developer.android.com.