Some notifications are used to display a task that is underway and may even include information on progress or state.
If we are going to support Android versions prior to 3.0, we will have to install the Xamarin Support Library v4 NuGet or component into our project.
To show progress in a notification, we can use a progress bar and update the notification as progress is made:
SetAutoCancel()
method, we use SetOngoing()
method:var notification = new NotificationCompat.Builder(this) .SetSmallIcon(Android.Resource.Drawable.StatNotifySync) .SetContentTitle("Simple Notification") .SetContentText("Starting Work!") .SetOngoing(true);
notification.SetProgress(0, 0, true);
notification.SetProgress(100, 27, false);
NotificationManager
instance with the same notification ID:manager.Notify(notificationId, notification.Build());
Cancel()
method with the notification ID:manager.Cancel(notificationId);
Because tasks take some time to complete, we may want to report the progress or the state of the task. Notifications provide a few means of showing such progress. We could use a normal text message to display the state, or we could use a progress bar to show the progress.
To display a progress bar, we use the SetProgress()
method. The progress bar can either have a specific progress or be indeterminate. For a specific progress, we specify the maximum and progress values along with false
. For indeterminate progress, we pass 0
to both the maximum and progress parameters, but true
for indeterminate.
To prevent the notification from being dismissed by the user, we do not specify the SetAutoCancel()
method as true
, but rather the SetOngoing()
method. This will prevent the notification from being dismissed by the user, even when they swipe the notification out of the notification drawer.
To update the notification once displayed, we simply have to invoke the Notify()
method again. We must pass the same notification ID; otherwise, a new notification will be created. Every time the notification changes, we invoke the Notify()
method.
Once the task has completed, we can update the notification with a dismissible notification, or we can manually remove the notification from the notification drawer. Cancelation is done by invoking the Cancel()
method on the NotificationManager
instance, providing the ID of the notification that we want to cancel.