Android notifications using MAUI (Part 7 of 10)

In this post we’re going to cover the tutorial Notifications Tutorial Part 7 – NOTIFICATION GROUPS – Android Studio Tutorial and we’re going to be adding a notification groups to our channel 2 code.

Overview

In this code we’re going to send notifications to a group. They will initially appear as different notifications but will then get grouped together.

Implementation

We’re going to overwrite/reuse our SendOnChannel2 method, first we’ll create two separate notifications but assign them to the same group, like this

var notification1 = new NotificationCompat.Builder(this, MainApplication.Channel2Id)
  .SetSmallIcon(Resource.Drawable.abc_btn_check_material)
  .SetContentTitle("Title 1")
  .SetContentText("Message 1")
  .SetPriority(NotificationCompat.PriorityLow)
  .SetGroup("example_group")
  .Build();

var notification2 = new NotificationCompat.Builder(this, MainApplication.Channel2Id)
  .SetSmallIcon(Resource.Drawable.abc_btn_check_material)
  .SetContentTitle("Title 2")
  .SetContentText("Message 2")
  .SetPriority(NotificationCompat.PriorityLow)
  .SetGroup("example_group")
  .Build();

We’re created the example_group but other than that you should be familiar with the way we create notifications.

Next we need a notification to become the summary notification (i.e. displays altogether in the same group) as these notification currently will simply be displays as two distinct notifications. So we add another notification like this

var summaryNotification = new NotificationCompat.Builder(this, MainApplication.Channel2Id)
  .SetSmallIcon(Resource.Drawable.abc_btn_colored_material)
  .SetStyle(new NotificationCompat.InboxStyle()
    .AddLine("Title 2 Message 2")
    .AddLine("Title 1 Message 1")
    .SetBigContentTitle("2 new messages")
    .SetSummaryText("user@example.com"))
  .SetPriority(NotificationCompat.PriorityLow)
  .SetGroup("example_group")
  .SetGroupAlertBehavior(NotificationCompat.GroupAlertChildren)
  .SetGroupSummary(true)
  .Build();

The main lines to look at are the last three. Again we set the group to the same as the other notifications but now we give this one a different alter behaviour and set it to become the group summary.

Finally let’s simulate messages arriving then see the grouping happen, so add the following the the method

Thread.Sleep(2000);
_notificationManager.Notify(2, notification1);
Thread.Sleep(2000);
_notificationManager.Notify(3, notification2);
Thread.Sleep(2000);
_notificationManager.Notify(4, summaryNotification);

Again a warning, this is not (as hopefully is obvious) good real world practise, for starters this method may be called on the main thread, depending upon your implementation and hence block that thread.

Code

Code for this an subsequent posts is found on my blog project.