Skip to main content

Command Palette

Search for a command to run...

How to Implement Firebase Push Notifications in a .NET MAUI Hybrid App

Integrate Firebase Push Notifications in .NET MAUI Hybrid App (Android Support)

Updated
4 min read
How to Implement Firebase Push Notifications in a .NET MAUI Hybrid App

Step 1: Add Firebase Configuration Files

Add google-services.json for Android

  1. Go to the Firebase Console.

  2. Create a new project or select an existing one.

  3. Navigate to Project Settings > General.

  4. In the "Your apps" section, register your Android app.

  5. Follow the instructions to download the google-services.json file.

  6. Place it in your project under Platforms/Android.

Set Build Action

  1. Right-click the google-services.json file in Solution Explorer.

  2. Choose Properties.

  3. Set Build Action to GoogleServicesJson.

Step 2: Create a .NET MAUI Hybrid Project

In Visual Studio:

  • Create a new project using the .NET MAUI Blazor App template.

  • This enables you to mix web and native mobile functionality using Razor and C#.

Step 3: Install Required NuGet Packages

Install the following packages via NuGet:

Plugin.Firebase
Plugin.Firebase.Crashlytics
Plugin.Firebase.CloudMessaging

Step 4: Handle Notification Permissions (Android)

In your AndroidManifest.xml, add the necessary permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

Step 5: Android Firebase Initialization

Create CrossFirebase Class

Inside Platforms/Android, create a file named CrossFirebase.cs:

public static class CrossFirebase
{
    public static void Initialize(
        Activity activity,
        CrossFirebaseSettings settings,
        FirebaseOptions firebaseOptions = null,
        string name = null)
    {
        if(firebaseOptions == null) {
            FirebaseApp.InitializeApp(activity);
        } else if(name == null) {
            FirebaseApp.InitializeApp(activity, firebaseOptions);
        } else {
            FirebaseApp.InitializeApp(activity, firebaseOptions, name);
        }

        if(settings.IsAnalyticsEnabled) {
            FirebaseAnalyticsImplementation.Initialize(activity);
        }
    }
}

Add Required Resources

Create a file strings.xml under Platforms/Android/Resources/values:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="com.google.firebase.crashlytics.mapping_flied_id">none</string>
    <string name="com.crashlytics.android.build_id">1</string>
</resources>

Step 6: Configure MauiProgram.cs

Update MauiProgram.cs file to register Firebase services:

#if IOS
using Plugin.Firebase.Bundled.Platforms.iOS;
#elif ANDROID
using Plugin.Firebase.Bundled.Platforms.Android;
#endif

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>()
               .RegisterFirebaseServices()
               .ConfigureFonts(fonts =>
               {
                   fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
               });

        builder.Services.AddMauiBlazorWebView();

#if DEBUG
        builder.Services.AddBlazorWebViewDeveloperTools();
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }

    private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
    {
        builder.ConfigureLifecycleEvents(events =>
        {
#if IOS
            events.AddiOS(iOS => iOS.WillFinishLaunching((app, _) =>
            {
                CrossFirebase.Initialize(CreateCrossFirebaseSettings());
                return false;
            }));
#elif ANDROID
            events.AddAndroid(android => android.OnCreate((activity, _) =>
            {
                var settings = CreateCrossFirebaseSettings();
                CrossFirebase.Initialize(activity, settings);
            }));
#endif
        });

        builder.Services.AddSingleton(_ => CrossFirebaseAuth.Current);
        builder.Services.AddSingleton(_ => CrossFirebaseCloudMessaging.Current);
        return builder;
    }

    private static CrossFirebaseSettings CreateCrossFirebaseSettings()
    {
        return new CrossFirebaseSettings(
            isAuthEnabled: true,
            isCloudMessagingEnabled: true,
            isCrashlyticsEnabled: true
        );
    }
}

Step 7: Create Firebase Admin SDK to Send Notifications

  • Download firebase-adminsdk.json

    1. Go to Firebase Console > Project Settings > Service Accounts

    2. Click Generate new private key

    3. Save the file as firebase-adminsdk.json in your project

Create PushNotification.cs

using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using Message = FirebaseAdmin.Messaging.Message;
using Notification = FirebaseAdmin.Messaging.Notification;

public class PushNotification
{
    private readonly FirebaseMessaging _firebaseMessaging;

    public PushNotification()
    {
        if (FirebaseApp.DefaultInstance == null)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("firebase-adminsdk.json") 
            });
        }

        _firebaseMessaging = FirebaseMessaging.DefaultInstance;
    }

    public async Task SendPushNotification(string deviceToken, string title, string body, object data)
    {
        if (deviceTokens.Any())
        {
            var message = new Message()
            {
                Token = deviceToken,
                Notification = new Notification()
                {
                    Title = title,
                    Body = body,
                    ImageUrl = "https://media.istockphoto.com/id/472909414/photo/demo-sign-colorful-tags.jpg?s=612x612&w=0&k=20&c=JD4iYaMoe4x--zJrltwiQzZdDyvtrRuNBK0uQ80tdXg="
                },
                Data = new Dictionary<string, string>
                {
                    { "click_action", "FLUTTER_NOTIFICATION_CLICK" },
                    { "target", "counter" },
                    { "extraData", JsonConvert.SerializeObject(data) }
                }
            };

            try
            {
                var response = await _firebaseMessaging.SendAsync(message);
                Log.Information($"Push Notification sent successfully. Message ID: {response}");
            }
            catch (Exception ex)
            {
                Log.Error($"Error sending push notification: {ex.Message}");
            }
        }
    }

Register the Service

In MauiProgram.cs, register the service:

builder.Services.AddSingleton<PushNotification>();

Step 8: Sending Notification from UI (Blazor)

In Home.razor:

@page "/"
@using MauiNotificationApp.Services
@inject NavigationManager Navigation
@inject PushNotification PushNotification

<h1>Hello, world!</h1>
Welcome to your new app.

<div class="mt-4">
    @if (!string.IsNullOrEmpty(responseMessage))
    {
        <div class="@(isSuccess ? "text-success" : "text-danger")">
            @responseMessage
        </div>
    }

    @if (isLoading)
    {
        <p>Processing...</p>
    }

    <button class="btn btn-success" @onclick="SendNotification" disabled="@isLoading">Send Notification</button>
</div>

@code {
    private bool isLoading = false;
    private bool isSuccess = false;
    private string responseMessage = string.Empty;
    private string fcmToken = string.Empty;
    private string errorMessage = string.Empty;
    private string successMessage = string.Empty;

    // Get FCM token and store it in a variable
    protected override async Task OnInitializedAsync()
    {
        await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
        fcmToken = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
        Console.WriteLine($"FCM token: {fcmToken}");
    }

    private async Task SendNotification()
    {
        if (string.IsNullOrEmpty(fcmToken))
        {
            errorMessage = "FCM token is not available. Please initialize Firebase first.";
            return;
        }

        isLoading = true;
        errorMessage = string.Empty;
        successMessage = string.Empty;

        try
        {
            var title = "Test Notification";
            var body = "This is a test notification";
            var data = new
            {
                Type = "Push Notification",
                Title = title,
                Message = body,
                Timestamp = DateTime.Now.ToString("o")
            };

            await PushNotification.SendPushNotification(fcmToken, title, body, data);
            successMessage = "Notification sent successfully!";
        }
        catch (Exception ex)
        {
            errorMessage = $"Error sending notification: {ex.Message}";
            Console.WriteLine($"Notification Error: {ex}");
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }
}

You've now successfully integrated Firebase Push Notifications into your .NET MAUI Hybrid App!

Diagram:

R

very nice article. I was looking such solution. I have one query here, how to send on another devices like same app its should show to another devices not withing devices from where you sending notification based on each android has a unique devices no, One person send other receive like we send whats app based on mobile no but we want to do based on devices ID