.Net Maui Local Notifications Android And Ios Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of .NET MAUI Local Notifications Android and iOS

.NET MAUI Local Notifications for Android and iOS

Overview

.NET Multi-platform App UI (.NET MAUI) allows developers to build applications for multiple platforms, including Android and iOS, using a single codebase. Local notifications are a key feature that enables apps to communicate with users even when the app is not in the foreground or is closed entirely. Implementing local notifications in .NET MAUI involves configuring both the Android and iOS platforms to ensure seamless functionality across devices.

Important Information and Steps

1. NuGet Package Installation

The first step in implementing local notifications is to add the necessary NuGet package to your project. For .NET MAUI, the package Plugin.LocalNotifications is widely used and well-supported.

dotnet add package Plugin.LocalNotifications
2. Platform-Specific Setup
Android
  • Manifest.xml: Ensure that necessary permissions are declared in the AndroidManifest.xml file. These permissions are typically handled by the Plugin.LocalNotifications package, but you might need to verify them in special cases.
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.VIBRATE" />
  • MainApplication.cs: Initialize the local notification service in your MainApplication.cs file.
using Android.App;
using Android.Runtime;
using Plugin.LocalNotifications;
using Microsoft.Maui.ApplicationModel;

[assembly: UsesPermission(Android.Manifest.Permission.PostNotifications)]

namespace YourAppName.Android
{
    [Application]
    public class MainApplication : MauiApplication
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Initialize local notifications (if required)
            CrossLocalNotifications.Current.Initialize();
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
iOS
  • Info.plist: Update your Info.plist file to request permission for notifications.
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>remote-notification</string>
</array>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app requires location access for notifications.</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>location-services</string>
</array>
  • AppDelegate.cs: Configure the notification settings in the AppDelegate.cs file.
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Hosting;
using Plugin.LocalNotifications;

namespace YourAppName.iOS
{
    [Register("AppDelegate")]
    public class AppDelegate : MauiUIApplicationDelegate
    {
        protected override Microsoft.Maui.Hosting.MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            // Register for notification permissions
            CrossLocalNotifications.Current.Configure();

            return base.FinishedLaunching(uiApplication, launchOptions);
        }
    }
}
3. Implementing Notifications
Sending a Notification

You can send a local notification using the LocalNotificationCenter class. Here is a basic example:

using Plugin.LocalNotifications;
using System;

public class NotificationService
{
    public void ScheduleNotification()
    {
        var notification = new NotificationRequest
        {
            NotificationId = 100,
            Title = "Your App Title",
            Description = "This is a local notification from your app!",
            Schedule = new NotificationRequestSchedule
            {
                NotifyTime = DateTime.Now.AddSeconds(10), // Schedule to trigger after 10 seconds
            }
        };

        CrossLocalNotifications.Current.Show(notification);
    }
}
Handling Tapped Notifications

You can handle tap events on the notifications to perform actions when the user interacts with them.

CrossLocalNotifications.Current.NotificationTapped += NotificationTapped;

private void NotificationTapped(NotificationTappedEventArgs e)
{
    Debug.WriteLine("Notification tapped: " + e.GetActionValue);

    // Perform any action based on the notification tapped
}
4. Testing & Troubleshooting
  • Testing on Physical Devices: Local notifications behave differently on emulators and simulators compared to physical devices. It’s preferable to test on a physical device to ensure notifications are configured correctly.
  • Debugging: Use logging and debugging tools to track any issues with permissions or notification delivery.
  • Platform-specific Issues: Refer to the official documentation for any platform-specific quirks or changes related to notifications.
5. Best Practices
  • User Consent: Ensure you obtain explicit consent from users before requesting notification permissions. Provide a clear explanation to users about why the app needs to send notifications.
  • Battery Efficiency: Minimize the frequency and impact of notifications to preserve battery life and avoid annoying users.
  • Personalization: Allow users to customize notification settings, such as frequency, types, and delivery times, to enhance user experience.
  • Permissions: Always handle permissions gracefully. If a user denies a notification request, inform them of the potential impact and provide guidance on how to change their decision.

Conclusion

Implementing local notifications in .NET MAUI for Android and iOS involves careful configuration and adherence to platform-specific guidelines. By following the steps outlined above, you can effectively integrate local notifications into your app, enhancing user engagement and satisfaction.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement .NET MAUI Local Notifications Android and iOS

Prerequisites

  1. Visual Studio 2022: Ensure you have the latest version of Visual Studio with .NET MAUI installed.
  2. Android SDK/NDK: Make sure the Android SDK and NDK are installed.
  3. iOS Development: You must be on a Mac for iOS development, or you can use a Mac in the cloud.

Step-by-Step Guide for Local Notifications

1. Create a New .NET MAUI Project

  • Open Visual Studio.
  • Go to Create a new project.
  • Select MAUI App.
  • Click Next.
  • Enter your project name, for example, LocalNotificationsDemo.
  • Choose the location where you want to save the project.
  • Click Next and then Create.

2. Install Required NuGet Packages

For handling notifications, you can use the Plugin.LocalNotifications NuGet package. It simplifies the process of creating local notifications.

  • Right-click on your solution in the Solution Explorer.
  • Select Manage NuGet Packages for Solution.
  • Go to the Browse tab and search for Plugin.LocalNotifications.
  • Install the package for all projects in your solution (.NET MAUI, Android, and iOS).

3. Initialize the Plugin in Andoid

Navigate to your Android project and make the following changes:

  • Open the MainActivity.cs file.
  • Include the necessary namespace:
using Plugin.LocalNotification;
  • Inside the OnCreate method, add the following code:
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    LocalNotification.Platform.Init(this);
}
  • In MainActivity.cs, override the OnNewIntent method:
protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);
    LocalNotification.Platform.OnNewIntent(intent);
}

4. Initialize the Plugin in iOS

Navigate to your iOS project and make the following changes:

  • Open the AppDelegate.cs file.
  • Include the necessary namespace:
using Plugin.LocalNotification;
  • Inside the FinishedLaunching method, add the following code:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    LocalNotification.Platform.Init(options.GetNotificationResponse());
    return base.FinishedLaunching(app, options);
}
  • Override the ReceivedLocalNotification method:
public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
{
    LocalNotification.Platform.ReceivedLocalNotification(notification);
}

5. Create Local Notifications

Now, you can create local notifications in your .NET MAUI shared code.

  • Open the MainPage.xaml.cs file or wherever you want to trigger notifications.
  • Add the following code in a method, such as the OnAppearing or a button click event:
private void ScheduleNotification()
{
    var notification = new NotificationRequest
    {
        NotificationId = 100,
        Title = "Hello!",
        Description = "This is a local notification from .NET MAUI",
        Schedule = null // For immediate notification
    };

    LocalNotificationCenter.Current.Show(notification);
}

6. Permissions

For iOS, you may need to request explicit permission to send local notifications.

  • Open the Info.plist file in the iOS project.
  • Add the following key-value pair:
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
</array>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>NSLocalNotificationUsageDescription</key>
<string>Your message to the user about notifications goes here</string>
  • In the AppDelegate.cs file, request permissions:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    LocalNotification.Platform.Init(options.GetNotificationResponse());
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
    {
        Console.WriteLine($"Request Authorization {approved}");
    });

    return base.FinishedLaunching(app, options);
}

7. Testing

  • For Android: Deploy your application to an emulator or a physical device. Trigger the notification from your app, and you should see it pop up.
  • For iOS: Deploy your application to a physical device (the simulator does not support local notifications). Trigger the notification from your app, and you should see it pop up.

Conclusion

This guide should help you set up local notifications in a .NET MAUI application for both Android and iOS. You can customize the notifications with additional properties like BadgeNumber, Sound and Category, depending on your needs. Happy coding!

Full Example Code

Android MainActivity.cs

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;

namespace LocalNotificationsDemo;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        LocalNotification.Platform.Init(this);
    }

    protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        LocalNotification.Platform.OnNewIntent(intent);
    }
}

iOS AppDelegate.cs

using Foundation;
using Microsoft.Maui;
using Microsoft.Maui.Hosting;
using UIKit;
using UserNotifications;
using Plugin.LocalNotification.Platforms.iOS;

namespace LocalNotificationsDemo;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        LocalNotification.Platform.Init(options.GetNotificationResponse());
        UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
        {
            Console.WriteLine($"Request Authorization {approved}");
        });

        return base.FinishedLaunching(app, options);
    }

    public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
    {
        LocalNotification.Platform.ReceivedLocalNotification(notification);
    }
}

Shared Code MainPage.xaml.cs

using Plugin.LocalNotification;
using System.Diagnostics;

namespace LocalNotificationsDemo;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void OnScheduleNotificationClicked(object sender, EventArgs e)
    {
        ScheduleNotification();
    }

    private void ScheduleNotification()
    {
        var notification = new NotificationRequest
        {
            NotificationId = 100,
            Title = "Hello!",
            Description = "This is a local notification from .NET MAUI",
            Schedule = null // For immediate notification
        };

        LocalNotificationCenter.Current.Show(notification);
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="LocalNotificationsDemo.MainPage">

    <StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
        <Button Text="Schedule Notification" Clicked="OnScheduleNotificationClicked" />
    </StackLayout>

</ContentPage>

Info.plist

Add the following under the <dict> tag in Info.plist:

Top 10 Interview Questions & Answers on .NET MAUI Local Notifications Android and iOS

Top 10 Questions and Answers about .NET MAUI Local Notifications for Android and iOS

1. What are Local Notifications, and How Do They Work in .NET MAUI?

2. How Do I Configure Local Notifications in .NET MAUI for Android?

Answer: Configuring local notifications for Android involves setting permissions and creating a notification channel. In your MainActivity.cs, you must request the necessary permissions and create a notification channel as Android Oreo (API 26) and above require it.

public override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    CreateNotificationChannel();
}

void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        var channel = new NotificationChannel("default", "Default", NotificationImportance.Default)
        {
            Description = "Description of the notification channel"
        };

        var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
}

3. How Do I Configure Local Notifications in .NET MAUI for iOS?

Answer: iOS requires no explicit configuration like Android. However, you need to request permission from the user. In AppDelegate.cs, you can request authorization for notifications.

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    var center = UNUserNotificationCenter.Current;
    center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound, (granted, error) =>
    {
        /* Handle approval */
    });

    return true;
}

4. How Can I Schedule a Simple Notification in .NET MAUI?

Answer: Scheduling a simple local notification can be done using the LocalNotificationService. Here's an example:

var notification = new NotificationRequest
{
    NotificationId = 1,
    Title = "Hey!",
    Description = "It's time!",
    Schedule = new NotifyLater(5) // Notify in 5 seconds
};

LocalNotificationCenter.Current.Show(notification);

5. Can I Set an Icon for Notifications on Android?

Answer: Yes, you can set a small icon for notifications on Android by providing a resource ID in the notification request.

var notification = new NotificationRequest
{
    NotificationId = 1,
    Title = "Hey!",
    Description = "It's time!",
    AndroidOptions = new AndroidOptions
    {
        SmallIcon = Resource.Drawable.notification_icon // Resource ID of your icon
    }
};

6. What If I Want to Repeat a Notification Regularly?

Answer: To schedule a repeating notification, use the Repeats property of NotifyLater or NotifyCalendar.

var notification = new NotificationRequest
{
    NotificationId = 1,
    Title = "Hey!",
    Description = "It's time!",
    Schedule = new NotifyCalendar
    {
        NotifyOn = NotifyOn.Weekdays, // Repeat on weekdays
        Time = new TimeSpan(10, 0, 0) // Notify at 10 AM
    },
    Repeats = true
};

7. Can I Handle Notification Taps in .NET MAUI?

Answer: Yes, you can handle notification taps by implementing the OnNotificationReceived method in your MainActivity.cs (for Android) and AppDelegate.cs (for iOS).

Android:

protected override void OnNewIntent(Intent intent)
{
    var notificationId = intent.GetIntExtra("NotificationId", -1);
    if (notificationId != -1)
    {
        HandleNotificationTapped(notificationId);
    }
    base.OnNewIntent(intent);
}

iOS:

public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
    completionHandler(UNNotificationPresentationOptions.Alert);
}

public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
    var notificationId = response.Notification.Request.Identifier;
    HandleNotificationTapped(notificationId);
}

8. Are There Any Platform-Specific Limitations?

Answer: Yes, both platforms have limitations. For instance, iOS restricts the number of pending notifications and the notification's content, while Android has strict policies regarding the notification's lifecycle and battery usage.

9. How Do I Cancel a Scheduled Notification in .NET MAUI?

Answer: You can cancel a scheduled notification using its ID.

LocalNotificationCenter.Current.Cancel(1); // Cancel notification with ID 1

10. Can I Customize the Alert Sound for Notifications?

Answer: Yes, you can specify a custom sound for notifications. For Android, place a sound file in Resources/raw, and for iOS, use a sound file in Bundle Resources.

Android:

var notification = new NotificationRequest
{
    AndroidOptions = new AndroidOptions
    {
        SoundName = "custom_sound.mp3"
    }
};

iOS: Use the UNUserNotificationCenter.Current.SetNotificationCategories method to specify custom actions.

You May Like This Related .NET Topic

Login to post a comment.