Android notifications using MAUI (Part 6 of 10)

In this post we’re going to cover the tutorial Notifications Tutorial Part 6 – PROGRESS BAR NOTIFICATION – Android Studio Tutorial and we’re going to be adding a progress bar to our notification.

Overview

You may have a requirement to show a progress bar notification, for example a process to download a file or the likes takes place, your application goes into the background but we keep getting feedback via the notification’s progress bar.

Implementation

We’ll leave channel 1 for now and simply add our progress bar to SendOnChannel2. We’ll change the content title to “Download” and content text “Download in progress), we’ll add a progress bar to the notification and set it’s max and current value. The progress bar will be determinate i.e. it’s not one of those progress bars that bounces back and forth indeterminate.

We’re also going to simulate updates to the progress bar within this method. Let’s look at the SendOnChannel2 method

const int progressMax = 100;
var notification = new NotificationCompat.Builder(this, MainApplication.Channel2Id)
   .SetSmallIcon(Resource.Drawable.abc_btn_check_material)
   .SetContentTitle("Download")
   .SetContentText("Download in progress")
   .SetPriority(NotificationCompat.PriorityLow)
   .SetOngoing(true)
   .SetOnlyAlertOnce(true) // with high priority, stops the popup on every update
   .SetProgress(progressMax, 0, false);

   _notificationManager.Notify(2, notification.Build());

   // simulate progress, such as a download
   Task.Run(() =>
   {
      Thread.Sleep(2000);

      for (var progress = 0; progress <= progressMax; progress += 10)
      {
         notification.SetProgress(progressMax, progress, false);
         // same id (2) to ensure overwrite/updates existing
         _notificationManager.Notify(2, notification.Build());

         Thread.Sleep(1000);
      }

      notification.SetContentText("Download finished")
         .SetOngoing(false)
         .SetProgress(0, 0, false);

      // same id (2) to ensure overwrite/updates existing
      _notificationManager.Notify(2, notification.Build());
   });

This is pretty simple and hopefully fairly sel-explanatory. But to summarise, we add a progress bar, set it’s starting point then in a separate thread, pause for a bit, so the user would see the download simulation start, then update the progress bar and pause to just make it look like it’s busy downloading something. All this happens against the same notification id, hence updates the current progress. Eventually we finish the download simulation and update the progress bar to show this completed state.

Code

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