HomePush NotificationsPush Notifications in .NET MAUI with FCM – Android Part

Push Notifications in .NET MAUI with FCM – Android Part

Setting up Firebase Cloud Messaging for Android in .NET MAUI is more straightforward than iOS, but there are still important configuration steps and potential pitfalls. This guide walks you through the complete Android FCM implementation, helping you avoid common issues and get notifications working quickly.

You’ll learn how to configure Firebase for Android, set up the necessary Android permissions and services, implement the .NET MAUI code, and test your push notifications.

Why Firebase Cloud Messaging for .NET MAUI?

Firebase Cloud Messaging provides a reliable and scalable solution for sending push notifications to both iOS and Android devices. For .NET MAUI developers, FCM offers:

    • Cross-platform consistency with a unified API
    • Free tier supporting millions of messages monthly
    • Advanced targeting features for user segmentation
    • Built-in analytics for tracking notification performance

Prerequisites

Before implementing push notifications in .NET MAUI with FCM, ensure you have:

    • .NET MAUI SDK 8.0 or higher
    • Visual Studio 2022 or compatible IDE
    • Android SDK and emulator or physical device
    • Firebase project set up

Estimated implementation time: 1-2 hours

Step 1: Configure Firebase Project

1.1 Register Android App in Firebase

    1. Open the Firebase Console
    2. Create a new project or select an existing one
    3. Click "Add app" → Android
    4. Enter your Bundle ID exactly as defined in your MAUI project:
<!-- In your .csproj under PropertyGroup -->
<ApplicationId>com.yourcompany.appname</ApplicationId>
    1. Download the google-services.json file
    2. Skip the additional Firebase setup steps for now

1.2 Add GoogleService-Info.plist to Your Project

Add the file to your project and configure the build action:

<ItemGroup Condition="'$(TargetFramework)' == 'net8.0-android'">
  <GoogleServicesJson Include="google-services.json" />
</ItemGroup>

Step 2: Android Manifest Configuration

Add the following permissions and services to your Platforms/Android/AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true">
		<receiver
    android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
    android:exported="false" />
		<receiver
			android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
			android:exported="true"
			android:permission="com.google.android.c2dm.permission.SEND">
			<intent-filter>
				<action android:name="com.google.android.c2dm.intent.RECEIVE" />
				<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
				<category android:name="${applicationId}" />
			</intent-filter>
		</receiver>
	</application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
</manifest>

Step 3: .NET MAUI Implementation

3.1 Install NuGet Package

Install the Firebase Cloud Messaging package:

dotnet add package Plugin.Firebase.CloudMessaging

3.2 Configure MauiProgram.cs

using Plugin.Firebase.CloudMessaging;

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

namespace YourMAUIApp
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .RegisterFirebaseServices()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("Nunito-Regular.ttf", "NunitoRegular");
                    fonts.AddFont("Nunito-Semibold.ttf", "NunitoSemibold");
                    fonts.AddFont("Nunito-ExtraBold.ttf", "NunitoExtrabold");
                });

#if DEBUG
    		builder.Logging.AddDebug();
#endif
            return builder.Build();
        }
        /// <summary>
        /// 
        /// 
        ///  Register Firebase Services
        ///  
        /// 
        /// </summary>
        private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
        {
            builder.ConfigureLifecycleEvents(events => {
#if IOS
                events.AddiOS(iOS => iOS.WillFinishLaunching((_, __) => {
                    CrossFirebase.Initialize();
                    FirebaseCloudMessagingImplementation.Initialize();
                    return false;
                }));
#elif ANDROID
                events.AddAndroid(android => android.OnCreate((activity, _) =>
                CrossFirebase.Initialize(activity)));
#endif
            });

            return builder;
        }    
    }
}

3.3 Android Platform-Specific Setup

Update Platforms/Android/MainActivity.cs:

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Plugin.Firebase.CloudMessaging;

namespace YourMAUIApp
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            HandleIntent(Intent);
            CreateNotificationChannelIfNeeded();
        }

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

        private static void HandleIntent(Intent intent)
        {
            FirebaseCloudMessagingImplementation.OnNewIntent(intent);
        }

        private void CreateNotificationChannelIfNeeded()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                CreateNotificationChannel();
            }
        }

        private void CreateNotificationChannel()
        {
            var channelId = $"{PackageName}.general";
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            var channel = new NotificationChannel(channelId, "General", NotificationImportance.Default);
            notificationManager.CreateNotificationChannel(channel);
            FirebaseCloudMessagingImplementation.ChannelId = channelId;
            
        }
    }
}

Choose production or development based on the setting you chose when registering your apns key.

Step 4: Implement Token Retrieval

using Plugin.Firebase.CloudMessaging;

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

    private async void OnCounterClicked(object sender, EventArgs e)
    {
        var status = await CheckAndRequestNotificationPermissionAsync();
        if (status == PermissionStatus.Granted)
        {
            await DisplayAlert("Success", "Notification permission granted!", "OK");
            
            try
            {
                var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
                Console.WriteLine($"FCM token: {token}");
                await Share.RequestAsync(new ShareTextRequest
                {
                    Text = token,
                    Title = "FCM Token"
                });
                    
                // For production: send token to your backend
                await SendTokenToBackend(token);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", $"Failed to get FCM token: {ex.Message}", "OK");
            }
        }
        else
        {
            await DisplayAlert("Notice", "Notification permission was not granted.", "OK");
        }
    }

    public async Task<PermissionStatus> CheckAndRequestNotificationPermissionAsync()
    {
        await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
        var status = await Permissions.CheckStatusAsync<Permissions.PostNotifications>();
        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.PostNotifications>();
        }
        return status;
    }

    private async Task SendTokenToBackend(string token)
    {
        // Implement your backend integration here
        // Typically POST to /api/devices/register
    }
}

Step 5: Testing Push Notifications in .NET MAUI

Test with Android Emulator:

    1. Build and run your app in the Android Emulator
    2. Launch the app and retrieve the FCM token
    3. Firebase Console → Cloud Messaging → Send test message
    4. Add the FCM token and send a test notification
    5. Verify the notification appears in the emulator

Test with Physical Device:

    1. Deploy to a physical device via USB debugging or APK
    2. Launch the app and retrieve the FCM token
    3. Use the same Firebase Console process to send test notifications
    4. Verify notifications work on the actual device

Both Android Emulator and physical devices support Firebase push notifications, so you can test your implementation in either environment.

Common Issues and Solutions

Issue 1: "Default FirebaseApp is not initialized" Error

Solution: This occurs when Firebase can't find or load your configuration. Fix it by:

    1. First: Verify your ApplicationId in .csproj exactly matches the package name in google-services.json
    2. Then: Delete bin and obj folders from your project
    3. Finally: Clean and rebuild your project

Issue 2: Token Generated but No Notifications

Solution: Check that notification permissions are enabled in your app settings and that you've created the notification channel properly.

Issue 3: NuGet Package Installation Fails (Long Path Issue)

Solution: Firebase packages can cause path length issues on Windows. The complete workaround is described here: Long Path Issue Solutions

Issue 4: Notifications Not Appearing on Device

Solution: Verify that your app has notification permissions enabled in Android settings and that the notification channel is properly configured.

Next Steps

You've successfully implemented Firebase push notifications in your .NET MAUI Android app!

Recommended next steps:

    1. Implement rich notifications with media and actions
    2. Build backend integration for automated notification campaigns
    3. Combine with iOS implementation for complete cross-platform coverage

Conclusion

Push notifications in .NET MAUI with Firebase Cloud Messaging for Android are relatively straightforward to implement once you understand the required configuration steps. The key is ensuring proper manifest permissions, notification channel setup, and Firebase service registration.

Unlike iOS, Android doesn't require complex certificate management, making the setup process much more developer-friendly. With proper configuration, you'll have a robust push notification system that works reliably across all Android devices.

Ready to implement iOS push notifications? Check out the iOS part of this series for complete cross-platform FCM coverage in .NET MAUI.

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *