Latest

Android notifications from beginners to advanced

  1. Introduction
  2. Making a notification
    2.1. Channels
    2.2. Title, Content, Image
    2.three. Types
    2.four. Actions
    2.5. Groups
    2.6. Badges
    2.7. Further customisation
  3. Greatest practices
  4. Assets

Notifications is a strong mechanism of Android OS and an ideal device which provides benefits to Users and Builders.

Notifications are part of a system; it means that you would be able to work together with a consumer when you might have useful info. It can be used as a further part of your software because you might present further info even when or if the Consumer doesn’t interact together with your software.

The pattern of Android notification

Allow us to discover Android history from the Notification viewpoint. We will see that notification was modified considerably. Initially, this element show info with small opportunity for interaction. These days we will show several types of knowledge in several ways and supply further actions for the Consumer. We will cut up all notification into totally different channels. Any Consumer can control which alerts shall be displayed beginning with Android Oreo (API 26). It signifies that we as a Builders should group our notifications properly. In any other case, we will have a state of affairs when all of them can be flip off.

Android application notification channelsSoftware channels

Android OS can display notifications on the house display, lock display, wearable units, and so on.

The “Notification badge” is a function that provides “badge” to the appliance icon when the app has a notification.

Android notification badge“Notification Badge” function

We’ll talk about all these subjects in the information. A demo app out there on the GitHub repository: NotificationDemo.

Every notification in Android Oreo or later wants a channel.

Let us begin with creating a channel and sending a notification with title, description and icon. Afterward, we’ll prolong an present one with further options.

Android notification with title, icon and descriptionPrimary notification with title, description and icon

Notification Channels

Creating a brand new channel

To begin with, it is best to register channel(s) if you need to send any notification on units with Android Oreo (8.zero) or larger. We will do it utilizing a createNotificationChannel() technique from a NotificationChannel class.

personal ultimate static String APP_PACKAGE = “com.alexzh.tutorial.notificationdemo”;
personal ultimate static String CITIES_CHANEL_ID = APP_PACKAGE + “.CITIES_CHANNEL”;
personal last static String APP_CHANEL_ID = APP_PACKAGE + “.APP_CHANNEL”;

NotificationChannel channel = new NotificationChannel(
chanelId,
chanelName,
chanelImportance);
channel.setDescription(chanelDescription);

We will enhance the code a bit bit when we wish to register a number of channels by adding perform for creating channels, and it is best to keep in mind that this API is on the market only for Android 8.zero (API 26).

@RequiresApi(api = Build.VERSION_CODES.O)
personal NotificationChannel createAppNotificationChanel(ultimate String chanelId,
last String chanelName,
last String chanelDescription,
last int chanelImportance)
NotificationChannel channel = new NotificationChannel(chanelId, chanelName, chanelImportance);
channel.setDescription(chanelDescription);
return channel;

@RequiresApi(api = Construct.VERSION_CODES.O)
personal void createNotificationChannels()
remaining Record channels = new ArrayList<>();
channels.add(createAppNotificationChanel(
CITIES_CHANEL_ID,
“Cities”,
“Information about cities”,
NotificationManagerCompat.IMPORTANCE_HIGH));

channels.add(createAppNotificationChanel(
APP_CHANEL_ID,
“Application”,
“General app updates”,
NotificationManagerCompat.IMPORTANCE_DEFAULT));

ultimate NotificationManager notificationManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);

if (notificationManager != null)
notificationManager.createNotificationChannels(channels);

After executing this code, we’ll register two channels (Software and Cities) for our software.

Android application notification channelsNotification channels

Deleting an present notification channel

A few of the present channels may be deprecated and not used any extra; it signifies that we will take away them.

personal ultimate static String APP_PACKAGE = “com.alexzh.tutorial.notificationdemo”;
personal last static String CITIES_CHANEL_ID = APP_PACKAGE + “.CITIES_CHANNEL”;

remaining NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.deleteNotificationChannel(CITIES_CHANEL_ID);

Navigate Consumer to channel settings

We will have a state of affairs when we wish to navigate a Consumer to the channel settings.

personal remaining static String APP_PACKAGE = “com.alexzh.tutorial.notificationdemo”;
personal remaining static String CITIES_CHANEL_ID = APP_PACKAGE + “.CITIES_CHANNEL”;

last Intent citiesChannelIntent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
citiesChannelIntent.putExtra(Settings.EXTRA_CHANNEL_ID, CITIES_CHANEL_ID);
citiesChannelIntent.putExtra(Settings.EXTRA_APP_PACKAGE, APP_PACKAGE);
mContext.startActivity(citiesChannelIntent);

Android notification channel detailsCities channel

Title, Content, Picture

We will start to create a notification after registering channel(s) because after it notifications may be despatched on any units.

Let us examine a picture with sample notification.

Explanation of basic parts of Android notificationRationalization of primary elements of the any notification

As you’ll be able to see we will discover the next part of the elemental notification:

In addition to it we will set a precedence and a method for our notification. The priority may be configured to any notification earlier than Android 8.zero and starting with this model of OS we will set priority just for channels.

I recommend utilizing the NotificationCompat class for working with Notifications because they can be sent on any gadget. Nevertheless, we should always add a brand new dependency.
implementation “com.android.support:support-compat:27.1.1”

We will use NotificationCompat.Builder for creating any notification.

NotificationCompat.Builder notificationBuilder = NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(information)
.construct();

In the case if you need to add a priority; you’ll be able to call setPriority with one of many following keys:

  • Much less essential:
    • NotificationCompat.PRIORITY_MIN (int: -2)
    • NotificationCompat.PRIORITY_LOW (int: -1)
  • Necessary:
    • NotificationCompat.PRIORITY_DEFAULT (int: zero)
  • Extra essential:
    • NotificationCompat.PRIORITY_HIGH (int: 1)
    • NotificationCompat.PRIORITY_MAX (int: 2)

Source: https://developer.android.com/reference/android/support/v4/app/NotificationCompat

We will move values in a variety -2 .. 2 to the setPriority technique.

Finally, we will send the notification:

remaining NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

if (notificationManager != null)
notificationManager.notify(NOTIFICATION_ID, notification);

Notification will probably be changed if you will use the same ID for multiple notifications.

Notification Types

Let us verify totally different types of notifications.

Android notifications stylesTypes of notifications

We will apply one among notification type using a setStyle technique. The picture above demonstrates totally different types.

BigTextStyle

Android notification BigTextStyleDemonstration of the BigTextStyle

The BigTextStyle makes use of for generating a large-format notification that often consists of a number of textual content.

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(information)
.setStyle(new NotificationCompat.BigTextStyle())

.construct();

BigPictureStyle

Android notification BigPictureStyleDemonstration of the BigPictureStyle

The BigPictureStyle uses for producing a large-format notification that often consists of a big image.

Bitmap image = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.amsterdam);
NotificationCompat.BigPictureStyle fashion = new NotificationCompat.BigPictureStyle().bigPicture(image);

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(information)
.setStyle(fashion)

.construct();

InboxStyle

Android notification InboxStyleDemonstration of the InboxStyle

The InboxStyle makes use of for producing a large-format notification that includes a listing of (up to 5) strings.

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentText(“5 new cities”)
.setStyle(new NotificationCompat.InboxStyle())

.construct();

MessagingStyle

Android notification MessagingStyleDemonstration of the MessagingStyle

The MessagingStyle makes use of for producing a large-format notification that features multiple messages from totally different individuals.

NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(“Alex”)
.setConversationTitle(“Order food”)
.addMessage(“Food order “, orderTimestamp, “test Inc.”)
.addMessage(“Receipt”, receiptTimestamp, “test payment Inc.”);

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.action_notification))
.setContentText(message)
.setStyle(messagingStyle)

.construct();

MediaStyle

Android notification MediaStyleDemonstration of the MediaStyle

The MediaStyle makes use of for media playback notifications.

Notification.Motion play = …
Notification.Motion cease = …
Notification.Action nextTrack = …
Notification.Motion prevTrack = …

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(information)
.setActions(play, prevTrack, nextTrack, cease)
.setStyle(new Notification.MediaStyle())

.build();

Notification Actions

The primary drawback with a present answer that we can’t interact with the notification. Allow us to repair this drawback by adding PendingIntent.

remaining Intent detailCityIntent = new Intent(mContext, DetailActivity.class);
detailCityIntent.putExtra(DetailActivity.CITY_ID, city.getId());

PendingIntent detailPendingIntent = PendingIntent.getActivity(
mContext,
zero,
detailCityIntent,
PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder notificationBuilder = NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(information)
.setContentIntent(detailPendingIntent)
.build();

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);

PengindIntent can have one of many following flags:

  • FLAG_CANCEL_CURRENT – Flag indicating that if the described PendingIntent already exists, the present one must be canceled earlier than generating a brand new one.
  • FLAG_NO_CREATE – Flag indicating that if the described PendingIntent does not already exist, then simply return null as an alternative of creating it.
  • FLAG_UPDATE_CURRENT – Flag indicating that if the described PendingIntent already exists, then hold it however exchange its additional knowledge with what is on this new Intent.
  • FLAG_IMMUTABLE – Flag indicating that the created PendingIntent must be immutable. Because of this the extra intent argument passed to the ship methods to fill in unpopulated properties of this intent can be ignored.
  • FLAG_ONE_SHOT – Flag indicating that this PendingIntent can be used only as soon as.

Source: https://developer.android.com/reference/android/app/PendingIntent

We will add actions to our notification. Let us enhance our notification and add motion which permits us to transfer to “All cities”.

The notification which incorporates title, textual content, icon and “All cities” motion

We should always create an Motion and put it into the NotificationCompat.Builder. Every action ought to have:

Let us create an action object.

remaining Intent allCitiesIntent = new Intent(mContext, MainActivity.class);
allCitiesIntent.putExtra(MainActivity.NOTIFICATION_ID_STR, MainActivity.NOTIFICATION_ID);

remaining PendingIntent allCitiesPendingIntent = PendingIntent.getActivity(
mContext,
zero,
allCitiesIntent,
PendingIntent.FLAG_CANCEL_CURRENT);

remaining NotificationCompat.Motion allCitiesIntent = new NotificationCompat.Motion(
R.drawable.ic_notification,
mContext.getString(R.string.action_all_cities),
allCitiesPendingIntent);

The final step is adding the motion to the notification. We will use two ways of doing it through the use of an Action object or passing few action parameters into addAction technique.

NotificationCompat.Builder notificationBuilder = NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)

.addAction(allCitiesPendingIntent)
.build();

One other method is a passing icon, title and motion intent to addAction technique.

NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)

.addAction(
R.drawable.ic_notification,
mContext.getString(R.string.action_all_cities),
allCitiesPendingIntent)
.build();

Lastly, we will interact with our notification and “All ciites” motion.

Notification Groups

All notifications don’t group by default.

Android ungrouped vs grouped notificationsComparing ungrouped and grouped notifications

Nevertheless, it is attainable to group them on the appliance degree. Allow us to attempt to do it for all notifications.

To begin with, we should always create a singular group key, which is a string value and update required notifications.

personal ultimate static String GROUP_KEY_CITIES = APP_CHANEL_ID + “.CITIES_GROUP”;

NotificationCompat.Builder notificationBuilder = NotificationCompat.Builder(mContext, GROUP_KEY_CITIES)

.setGroup(GROUP_KEY_CITIES)
.construct();

Afterwards, we should always create a summary notification.

remaining Notification summaryNotification = new NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setStyle(new NotificationCompat.InboxStyle())
.setGroup(GROUP_KEY_CITIES)
.setGroupSummary(true)
.build();

Nevertheless, in the case if you help units lower than Android 7.zero (API 24), you need to add .setContentText(SUMMARY).

Notifications group routinely if we’ve got extra then four notifications from the identical app.

Notification Badge

Notification Badges (also referred to as notification Dots) seems on software launchers icon, and it allows users be told about pending notification for the app. Users can work together with this notification in an analogous approach as with regular ones.

Android notification badge“Notification Badge” function

The notification badge up to date when any notification is accessible on your software.

We as builders have further prospects for customisation behaviour of this function.

Displaying badge

Notification badges are related with channels, it signifies that if you would like to change the behaviour of the channel which was register previously, it is best to create a brand new channel.

Whenever you don’t want to present badge for a notification channel you should use a setShowBadge(boolean) technique.

NotificationChannel channel = new NotificationChannel(chanelId, chanelName, chanelImportance);
channel.setDescription(chanelDescription);
channel.setShowBadge(false);

Notification rely
We will change a rely of notification which displays on the pop-up menu with notifications. It may be useful if you ship just one notification for many actions, like notification with a rely of unread messages.

Notification notification = new NotificationCompat.Builder(mContext, CITIES_CHANEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(“5 new cities”)
.setNumber(5)
.build();

Badge Icon Sort
We will customise badge a bit of bit. We’ve few risk for establishing the kind of the icon with setBadgeIconType for the notification. Nevertheless, this value may be ignored, if launcher does not help it.

Values which can be utilized for setBadgeIconType(int) technique:

  • BADGE_ICON_NONE (Integer: zero)
  • BADGE_ICON_SMALL (Integer: 1)
  • BADGE_ICON_LARGE (Integer: 2)

Customisation of the notifications

We’ve got many prospects for customisation notifications and channels. I would really like to show to you widespread prospects as an summary.

Notification channels:

  • Notification Lights – an enableLights permits you to enable notification lights if a device help it. Additionally, you possibly can choose a light-weight colour use setLightColor.
  • Notification Vibration – an enableVibration permits you to enable vibration and a setVibrationPattern permits you to change the vibration sample.
  • Notification Significance – a setImportance allows you to set importance for the current notification channel and you retrieve current importance use getImportance.
  • Notification Sound – a setSound allows you to set the sound for all notification for the required channel and getSound retrieve current sound settings.
  • Lock Display Visibility – a setLockScreenVisibility permits you to set the lock display visibility for all notifications for the current channel and also you retrieve current visibility setting with getLockscreenVisibility.
  • Show Badge – a canShowBadge permits you to change the potential of displaying badges for the present channel.

Notifications:

  • Colorized notification – a setColorized can be utilized when notification must be colorized. Additionally, a setColor technique allows you to set colour for colorized notification.

You possibly can set mild, vibration and sound for a single notification. Nevertheless, I recommend configure entire notification channel with mild, vibration and sound whether it is wanted for you.

Greatest practices

  • Send notification bundle when you could have many notifications, it improves interaction together with your app on wearable units
  • Use distinctive request code for various notifications; it permits you to be sure that intents can be totally different for each notification
  • Verify Material design: Notification
  • Check your code (Guide: Testing Android Notifications)

Assets