Building Notifications on Android O+
As a relatively new developer, I’m building an app for a friend’s bar, which should handle their events and some extras we decide upon along the way. As part of that, of course, we needed some notifications to let people know an event is happening that day, if they subscribe to it.
Notifications are relatively easy to make, but there are a few bugs you should be aware of. I also found the example code on Google’s website to have some bugs, so find below the version that works for me. I also recommend Google’s CodeLab for Notifications, although there’s a bit less handholding and the sample code used to have a year-old bug that no-one bothered to merge the pull request for.
There are three main steps to showing a notification on Oreo+:
1. Building the Notification Channel
If you’re deploying on a device that is API 26+ (Android 8.0 and newer), notifications will simply not show up if you don’t define a notification channel. However, this code won’t work on an older device, so the first thing we do is test whether we’re on Oreo.
private final static String manasia_notification_channel = "Manasia Event Reminder";
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//define the importance level of the notification
int importance = NotificationManager.IMPORTANCE_DEFAULT;
//build the actual notification channel, giving it a unique ID and name
NotificationChannel channel =
new NotificationChannel(manasia_notification_channel, manasia_notification_channel, importance);
//we can optionally add a description for the channel
String description = "A channel which shows notifications about events at Manasia";
channel.setDescription(description);
//we can optionally set notification LED colour
channel.setLightColor(Color.MAGENTA);
// Register the channel with the system
NotificationManager notificationManager = (NotificationManager) getApplicationContext().
getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Afterwards, we need three things to build the channel: the channel id, the channel name and the level of importance those notifications have. In this example, I’ve given the channel the same name and ID, since it shows up to the user under long press, and a normal level of importance since we don’t want them to be obnoxious.
Optionally, we can add a number of things to the notification, such as a description (don’t ask me where that shows up, I couldn’t find it in Android P), and other elements such as notification LED colour and vibration pattern (with `setVibrationPattern(new long[]{insert milliseconds pattern here})`).
Once we’re all set, all we need to do is fetch the NotificationManager and create the channel. Be careful though, once you submit the notification channel, you cannot make any changes to it! If you submit a new channel with the same name and description, the system will just ignore it as duplicate.
2. Building the PendingIntent
You want an Intent to have something happens when the user clicks the notification, and the way to do that is with a PendingIntent.
//create an intent to open the event details activity
Intent intent = new Intent(getApplicationContext(), EventDetail.class);
//put together the PendingIntent
PendingIntent pendingIntent =
PendingIntent.getActivity(getApplicationContext(), 1, intent, FLAG_UPDATE_CURRENT);
A pending intent contains a regular intent, meaning you can put anything and everything inside it using putExtra . You can also set flags to determine how the app behaves, such as clearing the stack.
The PendingIntent creator takes four arguments: context, requestCode, an intent and an optional flag. The request code is just an identifier, but please be aware that the intent won’t work if the requestCode is 0.
3. Creating and showing the notification
Having set up the NotificationChannel and the PendingIntent, we’re finally ready to create our notification!
private final static String manasia_notification_channel = "Manasia Event Reminder";
//get latest event details
String notificationTitle = "Manasia event: " + event.getTitle();
String notificationText = event.getDate() + " at Stelea Spatarul 13, Bucuresti";
//build the notification
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(getApplicationContext(), manasia_notification_channel)
.setSmallIcon(R.drawable.ic_manasia_small)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//trigger the notification
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(1, notificationBuilder.build());
First things first, we build the title and description of the notification from our event object.
Then, using a NotificationCompat.Builder , we define the details of the notification. The minimum amount of details that is mandatory is: a small icon, title, detail text, and the notification channel ID we defined at step 1.
Aside from those, I’ve added the PendingIntent we set up at step 2, the notification priority and the setAutoCancel flag so the notification is automatically dismissed when a user clicks on it.
Once we’ve set up all the details, we can go ahead and trigger the notification by calling the NotificationManagerCompat and giving it a notification id and calling build() on the NotificationCompat.Builder we just created above. The notification ID is just an identifier, but please be aware that the notification might not work if the notification id is 0.
And there we go, if you put these three parts together, the app will call a notification, and it will open your PendingIntent on click. There are a lot of things under the hood that Android does for you, and this may mean that your notification will behave differently on different API levels or even just devices.
Let me know if this article helped you, and if you have any questions or suggestions!
In a future article, I’ll try to cover the best way to schedule notifications , since I’m still researching that part to find the best solution.