Android notifications using MAUI (Part 9 of 10)

In this post we’re going to cover the tutorial Notifications Tutorial Part 9 – NOTIFICATION CHANNEL SETTINGS – Android Studio Tutorial and we’re going to be notification channel settings.

Overwrite

In a previous post we looked at the fact that we cannot change the notification settings once created, we need to uninstall and reinstall. This is ofcourse not a lot of help if, whilst our application is running it determines that the user should be given the opportunity to change a setting. For example let’s assume the user blocked a channel and now wants our application to notify them when something occurs within the application.

Ofcourse we could popup an alert saying “Go to the channel settings and unblock it” or better still we can alert them then display the settings.

Implementation

We’re going to change our MainActivity.SendOnChannel1 method to check if notifications are enabled and whether they’re blocked. So let’s first look at how we check if notifications are enabled.

We need access to the NotificationManagerCompat and we use it like this

if (!notificationManager.AreNotificationsEnabled())
{
  OpenNotificationSettings(context);
  return;
}

In this case we’re not even bothering to try to send notifications if they’re disabled, but we use our new method OpenNotificationSettings to show the settings screen (in a real world app we’d probably display and alert to asking them if they wish to change the settings etc.

[RequiresApi(Api = 26)]
private static void OpenNotificationSettings(Context context)
{
  // api 26
  if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
  {
    var intent = new Intent(Settings.ActionAppNotificationSettings);
    intent.PutExtra(Settings.ExtraAppPackage, context.PackageName);
    context.StartActivity(intent);
  }
  else
  {
    var intent = new Intent(Settings.ActionApplicationDetailsSettings);
    intent.SetData(Uri.Parse($"package:{context.PackageName}"));
    context.StartActivity(intent);
  }
}

Next in SendOnChannel1 we’re execute this code to check if the specific channel is blocked and again alert/open settings for the user if it is

if (Build.VERSION.SdkInt >= BuildVersionCodes.O && IsChannelBlocked(context, MainApplication.Channel1Id))
{
  OpenChannelSettings(context, MainApplication.Channel1Id);
  return;
}

IsChannelBlocked looks like this

[RequiresApi(Api = 26)]
private static bool IsChannelBlocked(Context context, string channelId)
{
  if (context.GetSystemService(NotificationService) is NotificationManager manager)
  {
    var channel = manager.GetNotificationChannel(channelId);
    return channel is { Importance: NotificationImportance.None };
  }

  return false;
}

Note that both these methods require API 21 or above.

Code

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