dcsimg
December 7, 2016
Hot Topics:

Creating Bundled Notifications with Android

By Henry Atwell

Nougat has already made its debut globally; however, there are still a number of features need to be explored by developers worldwide. One such aspect to discuss is "Bundled Notifications." Before discussing how developers can make best use of Bundled Notifications in Nougat 7.0, let us briefly discuss how notifications differ in Nougat from previous versions.

Notifications have been extended comprehensively in this recent release from Android. The default messaging app generates a good number of messages over time. Bundling historical notifications make it easier for users to access any number of notifications during a period. It is similar to stacking notifications one over another; however, in this case, you have all similar notifications stacked together, through one common app notification.

Imagine having too many notifications piled up within an app, and you have them grouped together, showing just one notification instead of too many of them appearing one above another. Clicking that one notification opens up all the notifications related to that app, with recent ones appearing right at the top. This is what you see in Nougat, unlike older Android versions that show individual notifications, appearing one below another. Just follow a systematic process for implementing these bundled notifications, and you can have app specific notifications bundled under a common header, with Nougat OS or future higher versions on your Android Smartphone.

The advantages of using bundled notifications are evident from the name itself. It is cumbersome to see a bunch of notifications appearing over one another, making things overwhelming. In case of bundled notifications, similar notifications within an app fit into a common bundle; therefore, they are displayed only when clicked by users.

Looking at Marshmallow devices, the notifications don't overwhelm users. However, there is less detailing, which restricts users from seeing individual notifications. With unread messages displayed, you don't have enough details telling more about the individual notifications.

Creating the NotificationBuilder Class

So, let's come down to our main discussion. The first thing you need to do is create a NotificationBuilder class, as shown in the following code segment:

final class NotificationBuilder {
   private static final String GROUP_KEY = "Messenger";
   private static final String NOTIFICATION_ID =
      "com.stylingandroid.nougat.NOTIFICATION_ID";
   private static final int SUMMARY_ID = 0;
   private final Context context;
   private final NotificationManagerCompat notificationManager;
   private final SharedPreferences sharedPreferences;

   static NotificationBuilder newInstance(Context context) {
      Context appContext = context.getApplicationContext();
      Context safeContext =
         ContextCompat.createDeviceProtectedStorageContext(appContext);
      if (safeContext == null) {
         safeContext = appContext;
      }
      NotificationManagerCompat notificationManager =
         NotificationManagerCompat.from(safeContext);
      SharedPreferences sharedPreferences =
         PreferenceManager.getDefaultSharedPreferences(safeContext);
      return new NotificationBuilder(safeContext,
         notificationManager, sharedPreferences);
   }
   private NotificationBuilder(Context context,
         NotificationManagerCompat notificationManager,
         SharedPreferences sharedPreferences) {
      this.context = context.getApplicationContext();
      this.notificationManager = notificationManager;
      this.sharedPreferences = sharedPreferences;
   }
   .
   .
   .
}

The notification messages need to be displayed even before users have unlocked the device. Before users reboot their device, this is to take place, through device storage making use of SharedPreferences. So, let us actually look at how to go about doing this.

final class NotificationBuilder {
   .
   .
   .
   void sendBundledNotification(Message message) {
      Notification notification =
         buildNotification(message, GROUP_KEY);
      notificationManager.notify(getNotificationId(), notification);
      Notification summary = buildSummary(message, GROUP_KEY);
      notificationManager.notify(SUMMARY_ID, summary);
   }
   private Notification buildNotification(Message message,
         String groupKey) {
      return new NotificationCompat.Builder(context)
         .setContentTitle(message.sender())
         .setContentText(message.message())
         .setWhen(message.timestamp())
         .setSmallIcon(R.drawable.ic_message)
         .setShowWhen(true)
         .setGroup(groupKey)
         .build();
   }
   private Notification buildSummary(Message message,
         String groupKey) {
      return new NotificationCompat.Builder(context)
         .setContentTitle("Nougat Messenger")
         .setContentText("You have unread messages")
         .setWhen(message.timestamp())
         .setSmallIcon(R.drawable.ic_message)
         .setShowWhen(true)
         .setGroup(groupKey)
         .setGroupSummary(true)
         .build();
   }
   private int getNotificationId() {
      int id = sharedPreferences.getInt(NOTIFICATION_ID,
         SUMMARY_ID) + 1;
      while (id == SUMMARY_ID) {
         id++;
      }
      SharedPreferences.Editor editor =
         sharedPreferences.edit();
      editor.putInt(NOTIFICATION_ID, id);
      editor.apply();
      return id;
   }
}

The sendBundledNotification() method, as seen above, allows you to build a new notification. This separates the whole thing into two parts—a summary notification, and the actual message notification. As seen from previous examples, each individual message that appeared on Nougat+ devices, is an example of message notification, whereas summary notifications are those single messages. There is binding between these two sections of notifications, using an identical group key known as setGroup() applied on the notification builder.

There is an important point to note here. A message notification gets posted using a notification ID that is uniquely generated, and a fixed ID is used to generate the summary message. This is helpful especially when you want different notifications for same message to come through a common notification for a summary. Ensure to flag the summary message; this can be done by calling setGroupSummary(true) right on the notification builder. Based on the official documentation, a summary notification is strongly recommended, telling it is more of a requirement than a recommendation.

It is a good practice to use NotificationCompat throughout while doing this. Because setGroupSummary(), as well as setGroup(), are the only available APIs in the API 20 series, you are bound to use them, especially when targeting the APIs below 20. So, now the only thing that remains is to make use of MessengerService to create notifications.

public class MessengerService extends GcmTaskService {
   private static final String TAG =
      MessengerService.class.getCanonicalName();
   private Messenger messenger;
   private ServiceScheduler serviceScheduler;
   private NotificationBuilder notificationBuilder;

   public MessengerService() {
   }
   @Override
   public void onCreate() {
      super.onCreate();
      messenger = Messenger.newInstance(this);
      serviceScheduler = ServiceScheduler.newInstance(this);
      notificationBuilder =
         NotificationBuilder.newInstance(this);
   }
   @Override
   public int onRunTask(TaskParams taskParams) {
      Message message = messenger.generateNewMessage();
      Log.d(TAG, message.toString());
      notificationBuilder.sendBundledNotification(message);
      serviceScheduler.scheduleService();
      return GcmNetworkManager.RESULT_SUCCESS;
   }
   @Override
   public void onDestroy() {
      messenger = null;
      serviceScheduler = null;
      super.onDestroy();
   }
}

Some Final Words and Summing Up Thoughts

Notifications play an important role in the lives of mobile app users. They are useful because you get to know everything that's happening, even if your app is closed. Notifications do tell you about everything new taking place with the app. Whether it's products or services, events, offers, discounts, updates, upgrades, app notifications, or bug/error detection, you have information regarding everything through messages popping up on your Smartphone, even if it's locked. Ensure that you take time to see them; it can make a big difference in the way you are using them.

So, that is all. Now you know how to create bundled notification, especially if you are an Android developer who cares about providing a wonderful app experience to the users. There are certainly other ways to present notifications; we'll explore them in our later articles. However, bundled notifications are among the hot favorites because they keep things clean enough, with everything arranged systematically.

About the Author

Henry Atwell is an Android app developer associated with Fusion Informatics, a custom Android application development company. He is an avid writer and often contributes to various blogs and Web sites.

# # #

This article was contributed. ©Developer.com. All Rights Reserved


Tags: Android, smartphone, Marshmallow, Nougat, bundled notifications




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel