Push notification on MAUI application using FCM

Sreejith Sreenivasan 896 Reputation points
2023-09-29T10:06:12.68+00:00

I am trying to implement push notification on my MAUI application using FCM. I follow this blog and I did everything as per the blog.

They suggest to install only 2 NuGet packages, Plugin.Firebase and Plugin.Firebase.Crashlytics. (I installed it by adding it on the .csproj like below)

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios' OR '$(TargetFramework)' == 'net7.0-android'">
    <PackageReference Include="Plugin.Firebase" Version="2.0.3" />
    <PackageReference Include="Plugin.Firebase.Crashlytics" Version="2.0.1" />
</ItemGroup>

After adding the packages I have removed Unsupported TargetFrameworks by removing the MAC and windows framework code from .csproj file.

Then added the google-services.json file to the root folder of the project. But GoogleServicesJson Build Action is not showing in the list (This is the very first problem I am facing). So I added it on the .csproj manually.

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

Then updated MauiProgram.cs like below:

using Microsoft.Maui.LifecycleEvents;
using Plugin.Firebase.Auth;
using Plugin.Firebase.Bundled.Shared;
#if IOS
using Plugin.Firebase.Bundled.Platforms.iOS;
#else
using Plugin.Firebase.Bundled.Platforms.Android;
#endif

namespace MauiFirebaseDemo;

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

        return builder.Build();
    }

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

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

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

But a lot of properties in the new code are not exist. Check the below screenshots:

1

Using section also has the same kind issues: But the packages mention under using section are not installed2

On android platform I have done the below set up.

At Platforms/Android/Resources/values added the following line to strings.xml:

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

Added the following ItemGroup to the.csproj file to prevent build errors:

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-android'">
    <PackageReference Include="Xamarin.Kotlin.StdLib.Jdk7" Version="1.7.10" ExcludeAssets="build;buildTransitive" />
    <PackageReference Include="Xamarin.Kotlin.StdLib.Jdk8" Version="1.7.10" ExcludeAssets="build;buildTransitive" />
</ItemGroup>

In the AndroidManifest.xml. Added the following code snippet to the tag :

<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>

Then updated MainActivity.cs like below:

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

namespace MauiFirebaseDemo;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, 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;
        //FirebaseCloudMessagingImplementation.SmallIconRef = Resource.Drawable.ic_push_small;
    }
}

Here also I am getting the same kind of error on code and using section:

3

Under using section:

4

Is this the right approach to implement push notification on MAUI? I saw a similar kind of implementation here too. How can I fix the error on MauiProgram.cs and MainActivity.cs? Should I install any other NuGet packages? How can I set GoogleServicesJson Build Action for google-services.json?

I have tried installing the Plugin.Firebase.CloudMessaging and Plugin.Firebase.Auth for resolving the errors on MauiProgram.cs and MainActivity.cs. And tried installing the Xamarin.GooglePlayServices.Basement for resolving the GoogleServicesJson Build Action, but no lucks.

All the errors are does not exist in the current context, that's why added screenshot in the question. Sample error details are added in text format below:

The name 'CrossFirebase' does not exist in the current context The type or namespace name 'Firebase' does not exist in the namespace 'Plugin' (are you missing an assembly reference?)

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,526 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 31,716 Reputation points Microsoft Vendor
    2023-10-02T07:36:48.3166667+00:00

    Hello,

    You added the Plugin.Firebase and Plugin.Firebase.Crashlytics packages, they are third-party tools.

    Please check the following:

    • You could try to manage NuGet Package from right-click of the project then install the latest version.
    • You could try to install the packages separately, then identity which package caused the problem. (It looks like all issues are in Plugin.Firebase package)
    • Please expand the Packages tab and check if the NuGet packages has been installed successfully. (I cannot install the packages for iOS via VS2022, and I try using VS for Mac, all issues disappeared)
    • Please modify the TargetFramework for Android only, then check if the problem on Android platform still occurs.
    <TargetFrameworks>net7.0-android</TargetFrameworks>
    

    For the Build Action issue, your settings are correct, please add the plist file as well. Since they are third-party tools and they list their support at GitHub, please connect the owners for further help.

    <ItemGroup Condition="'$(TargetFramework)' == 'net7.0-android'">
        <GoogleServicesJson Include="google-services.json" />
    </ItemGroup>
    
    <ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios'">
        <BundleResource Include="GoogleService-Info.plist" />
    </ItemGroup>
    

    Update

    Currently, we can determine this issue only occurs on iOS platform. And you could install the packages via VS for MAC. In addition, you could try to install the package by dotnet CLI as described in the blog you mentioned.

    what is dotnet CLI and how we can install packages using that?

    CLI means command-line interface, you could run dotnet add package XXX to install the package.

    Is it the Terminal under view option?

    Yes. For more details about the adding packages command, you can see dotnet add package command - .NET CLI | Microsoft Learn

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Mr Nams 1 Reputation point
    2024-03-05T11:35:08.5233333+00:00

    Hello,I could able to get Push notification using FCM, I want these notification when value in realtime database get updated.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.