Max Mannstein

Subscribe :)

Implementing Firebase Cloud Messaging in .NET MAUI (Android)

After setting up Firebase Cloud Messaging (FCM) for iOS, it’s time to configure push notifications for Android in .NET MAUI. Let’s get started!


Why Use Firebase Cloud Messaging?

FCM allows you to send push notifications to your Android and iOS users efficiently. This guide covers everything you need to set up FCM for Android in your .NET MAUI app.


Step 1: Add Your Android App in Firebase

  1. Register your app’s package name from AndroidManifest.xml.
  2. Download the google-services.json file.
  3. Place it in your .NET MAUI project’s solution folder and include it:
<ItemGroup Condition="'$(TargetFramework)' == 'net9.0-android'">
  <GoogleServicesJson Include="google-services.json" />
</ItemGroup>

Step 2: Modify Android Configurations

  • Add this entry in strings.xml (Platforms/Android/Resources/values):

<?xml version="1.0" encoding="utf-8" ?>
<resources>
	<string name="com.google.firebase.crashlytics.mapping_file_id">none</string>
</resources>
  • Update AndroidManifest.xml by adding these entries inside the <application> tag, so that it looks like this:
<?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: Configure MainActivity.cs for Notifications

Modify MainActivity.cs to handle FCM notifications:

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

namespace FirebaseCloudMessagingTutorial
{
    [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;
        }
    }
}

Step 4: Install Firebase Packages

  1. Install the required NuGet packages for Firebase Cloud Messaging.
  2. Add Firebase initialization to MauiProgram.cs:


using Plugin.Firebase.CloudMessaging;

#if IOS
using Plugin.Firebase.Core.Platforms.iOS;
#elif ANDROID
using Plugin.Firebase.Core.Platforms.Android;
#endifprivate 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;
}

Testing Push Notifications on Android

Step 1: Retrieve the Firebase Device Token

Add this code in MainPage.xaml.cs:

   private async void OnCounterClicked(object sender, EventArgs e)
   {
       await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
       var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
       Console.WriteLine($"FCM token: {token}");
   }

Step 2: Send a Test Notification

  1. Go to Firebase ConsoleCloud MessagingSend a Message.
  2. Enter title, body, and the FCM token.
  3. Select Android and send the message.
  4. Verify that the notification appears on your device.

Wrapping Up

Your .NET MAUI Android app is now set up with Firebase Cloud Messaging! 🚀

👉 If you found this guide helpful, share it and subscribe for more .NET MAUI tutorials!

1 comment on “Implementing Firebase Cloud Messaging in .NET MAUI (Android)

  1. await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
    How are we supposed to tell if it is valid or not, when it is a void? Shouldn’t it be a bool instead?

Leave a Reply

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