Android notifications using MAUI (Part 10 of 10)

In this post we’re going to cover the tutorial Notifications Tutorial Part 10 – DELETE NOTIFICATION CHANNELS – Android Studio Tutorial and we’re going to be look at deleting notification channels.

Overwrite

We can delete notification channels if they’re no longer required, so let’s create some code by changing the UI slightly and updating with a new message – ofcourse in a real-world scenario, it’s more likely you’re either deleting a channel that’s been dynamically created or deleting a legacy channel.

Implementation

Go to to MainPage.xaml and add

<Button Text="Delete Channels" Clicked="DeleteChannel_OnClick" Margin="10" />

In the code behind MainPage.xaml.cs add the following

private void DeleteChannel_OnClick(object sender, EventArgs e)
{
  _messenger.Send(new DeleteChannelData());
}

As you can see we’ve added a new class DeleteChannelData to be sent to anything that wishes to listen to tell them to delete a channel. The code for this is simply

public record DeleteChannelData;

(It’s just really the equivalent of a command).

In the Android MainActivity constructor, add

messenger.Register<DeleteChannelData>(this, (recipient, message) =>
{
  if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
  {
    if (GetSystemService(NotificationService) is NotificationManager manager)
    {
      // hard coded to delete channel 3
      //manager.DeleteNotificationChannel(MainApplication.Channel3Id);
      manager.DeleteNotificationChannelGroup(MainApplication.Group1Id);
    }
  }
});

So this receives the DeletChannelData message and deletes either channel 3 (commented out) or a given group via the NotificationManager. Notice this is NOT the NotificationManagerCompat.

Now if you run this (after running the version prior to this) and go to the settings page for your application’s notifications (Settings | Apps & notifications) you’ll noticed it says something like 2 categories deleted if you’re deleting Group1Id group. This is telling the user that something deleted the channels.

Code

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