Written by Adrian Kremski
Android Developer
Published October 13, 2016

Notifications: From zero to hero Android N* – part 1/3

If you are a newbie to the Android notifications, here are the very essentials you need to know to build them for the Android Platform. Including the definition itself, just to let you start the proper way. The more complex and entertaining ones are coming in part 2 and 3 of this series.

This article is the first one of a series of three. Each part describes the work of Android notifications. The second part is going to focus on the Android 5 and 6 edition. The last text will be mainly flashed on the lately released Android 7.

1. Notification – what’s that?

The answer to this question is rather obvious to all Android developers and because of it (and my laziness 🙂 ) I will just post a description from https://developer.android.com web page.

A notification is a message you can display to the user outside of your application’s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.

2. Sending basic notification

To create any notification on Android you should use the android.support.v7.app.NotificationCompat.Builder class.

(Since API Lvl 11 there is also the android.app.Notification.Builder class available but stick to the NotificationCompat.Builder if you want to support older devices)

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

(Don’t forget to add a compile 'com.android.support:appcompat-v7:23.4.0’ line to your gradle build)

So NotificationCompat.Builder is our mastermind… Let’s see what it has to offer.

notificationBuilder.setContentTitle("Notice me!")
        .setContentText("I am your first notification :)")
        .setSmallIcon(android.R.drawable.ic_dialog_email)
        .setAutoCancel(true)
        .setDefaults(defaults)
        .setTicker("Ticker");
  • setAutoCancel – by passing true, the notification will be dismissed automatically when the user clicks it
  • setDefaults – here we can specify what action should be triggered when the notification appears. Possible options are:
    • NotificationCompat.DEFAULT_ALL – default action
    • NotificationCompat.DEFAULT_SOUND – new notification will make a sound
    • NotificationCompat.DEFAULT_VIBRATE – vibrate the phone
    • NotificationCompat.DEFAULT_LIGHTS – use led lights
  • setSmallIcon – icon which will be displayed in the status bar when notification is active
  • setTicker – text will be displayed in the status bar for few seconds when notification appeared

Now that we have our notification setup, let’s send it.

To do that, we need to obtain the NotificationManager.

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

And post the notification with the notifying method.

int notificationId = 1;
notificationManager.notify(notificationId, notificationBuilder.build());

NotificationId that we send to our method can be used to work with an active notification later on.
For example, if you would like to update current notification then just resend it with different data (message, etc.) but with the same notificationId (if the previous notification has been removed, a new one will be created).

Cancelling notification is also really simple. Just pass NotificationId to cancel method of notificationManager.

notificationManager.cancel(notificationId);

Other dismiss options are either calling notificationManager.cancellAll() or letting user cancel the notification manually.

Result

ezgif.com-resize

3. Make notification do something

If you want to show the user the source of received notification, you should specify an appropriate action. We do this by creating a PendingIntent object and sending it to the notification during construction stage (don’t forget that most of the time you will probably need to create a back stack to allow the user to navigate properly within your app).

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

String url = "http://www.google.pl";

Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

PendingIntent pendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        openUrlIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );


notificationBuilder.setContentTitle("Notice me!")
        .setContentText("Click here to open " + url)
        .setSmallIcon(android.R.drawable.ic_dialog_email)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent);

notificationManager.notify(0, notificationBuilder.build());

In the end, by clicking on the created notification, you will be moved to http://google.pl website.

Result

ezgif.com-resize

4. Prettier notifications

Our previous examples are really basic and not so good looking. However Android 4.1 has introduced new Notification styles which gave the possibility to display longer text or an image.

Let’s see how we can upgrade them.

4.1 Big text notification

To show longer text, we need to create a basic instance of our message and then apply the style with chosen text by invoking method setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.big_text))).

private NotificationCompat.Builder basicNotification() {
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

    notificationBuilder.setContentTitle("Notice me!")
        .setSmallIcon(android.R.drawable.ic_dialog_email)
        .setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setTicker("Ticker");

    return notificationBuilder;
}

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intentWithDefinedAction = new Intent();

PendingIntent pi = PendingIntent.getActivity(this, 0,
    intentWithDefinedAction, PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = basicNotification()
    .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.big_text)))
    .addAction(android.R.drawable.ic_dialog_email, getString(R.string.action), pi).build();
notificationManager.notify(bigNotificationId, notification);

4.2 Inbox notification

Similar case to the previous section but now we are going to apply new NotificationCompat.InboxStyle() and specify the summary text.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

Intent intentWithDefinedAction = new Intent();

PendingIntent pi = PendingIntent.getActivity(this, 0, intentWithDefinedAction, PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = basicNotification()
    .setStyle(new NotificationCompat.InboxStyle()
    .addLine(getString(R.string.line_1))
    .addLine(getString(R.string.line_2))
    .addLine(getString(R.string.line_3))
    .addLine(getString(R.string.line_4))
    .setSummaryText("5 more lines"))
    .addAction(android.R.drawable.ic_dialog_email, getString(R.string.action), pi).build();

notificationManager.notify(inboxNotificationId, notification);

4.3 Big picture notification

The last example is also easy to understand. To show a picture, we just need a bitmap which we are passing to an instance of NotificationCompat.BigPictureStyle.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

Bitmap natureBitmap = decodeSampledBitmapFromResource(getResources(), R.drawable.nature, 100, 100);
Intent intentWithDefinedAction = new Intent();

PendingIntent pi = PendingIntent.getActivity(this, 0, intentWithDefinedAction, PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = basicNotification()
    .setStyle(new NotificationCompat.BigPictureStyle()
        .setBigContentTitle(getString(R.string.big_picture_title))
        .bigPicture(natureBitmap)
    )
    .addAction(android.R.drawable.ic_dialog_email, getString(R.string.action), pi).build();

notificationManager.notify(bigPictureNotificationId, notification);

Result
Screenshot_20160718-205804

Written by Adrian Kremski
Android Developer
Published October 13, 2016