Creating push notifications for Android in .NET MAUI
Tags: maui, android, firebase, dotnet
Published: 2023-07-05 22:58:20

Hello colleagues. In this article, I want to introduce you to Firebase notification implementation. It's a super easy realization and I show how.

##Creating Firebase project
Go to the [https://console.firebase.google.com](https://console.firebase.google.com) and click on the huge + and begin creating a project.


![1 step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h4u8y6mlrr8lh2ey8wz5.png)

Let's name the project "push-maui". Click "Continue".
In the second step leave it unchanged.


![2 step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g4x4vg9vzyrrbkc3veza.png)

In the last step select an account and click "Create project".

![3 step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q96fm6vkfvrzfaeyjpka.png)

After one minute - click "Continue".


![finish](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgsc4xr84417r1s5vo29.png)


##Creating MAUI project 
Let's create a new project:
```bash
dotnet new maui -n PushMauiSample
cd PushMauiSample
```
Open the solution in your favorite IDE. Before we begin implementing Firebase Cloud Messaging, let's add `Plugin.Firebase` package. I install an older version since it is compatible with JDK. The newest version has issues:
```bash
dotnet add package Plugin.Firebase 1.2.0
```

And also, for Android you need these packages:
```bash
dotnet add package Xamarin.Kotlin.StdLib.Jdk7
dotnet add package Xamarin.Kotlin.StdLib.Jdk8
```
Further, go to the `PushMauiSample.proj`, delete all non-android settings, and inject Google services. It should be something like that:
```xml
<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<TargetFramework>net7.0-android</TargetFramework>
		
		<OutputType>Exe</OutputType>
		<RootNamespace>PushMauiSample</RootNamespace>
		<UseMaui>true</UseMaui>
		<SingleProject>true</SingleProject>
		<ImplicitUsings>enable</ImplicitUsings>

		<!-- Display name -->
		<ApplicationTitle>PushMauiSample</ApplicationTitle>

		<!-- App Identifier -->
		<ApplicationId>com.companyname.pushmauisample</ApplicationId>
		<ApplicationIdGuid>d0db7add-d444-449e-bb11-c0ff3569174c</ApplicationIdGuid>

		<!-- Versions -->
		<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
		<ApplicationVersion>1</ApplicationVersion>

		<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
	</PropertyGroup>

	<ItemGroup>
		<!-- App Icon -->
		<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />

		<!-- Splash Screen -->
		<MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />

		<!-- Images -->
		<MauiImage Include="Resources\Images\*" />
		<MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />

		<!-- Custom Fonts -->
		<MauiFont Include="Resources\Fonts\*" />

		<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
		<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
	</ItemGroup>

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

	<ItemGroup>
		<PackageReference Include="Plugin.Firebase" Version="1.2.0" />
	</ItemGroup>

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

	<ItemGroup>
	  <MauiPlatformSpecificFolder Remove="Platforms\iOS\" />
	  <MauiPlatformSpecificFolder Remove="Platforms\MacCatalyst\" />
	  <MauiPlatformSpecificFolder Remove="Platforms\Tizen\" />
	  <MauiPlatformSpecificFolder Remove="Platforms\Windows\" />
	</ItemGroup>

</Project>

```

After that, you did it. Let's register the service. Add this code to `MauiProgram.cs`:
```C#
private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
	{
		builder.ConfigureLifecycleEvents(events =>
		{

			events.AddAndroid(android => android.OnCreate((activity, state) =>
				CrossFirebase.Initialize(activity, CreateCrossFirebaseSettings())));
		});

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

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

And sure, you should update this method:
```C#
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();
	}
```

##Registering an application
And now, let's return to Firebase Console and register the application. You should choose Android.


![select app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxsxnhyv26n3i6bibeku.png)

There are four steps. The more important is first. The Android package name is project id. Let's name it `dev.to.android.push`. Click the Register app.
In the next step, save `google-services.json` to the root of your project. Click Next.

![save servvices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u687rl9axyac2jatd9os.png)

The next steps without changes. In the end, click "Continue to console".

##A few settings and implementation
Let's return to `PushMauiSample.proj` and find this row:
```xml
<ApplicationId>com.companyname.pushmauisample</ApplicationId>
``` 
You should replace to `dev.to.android.push` name that we registered in the Firebase console. The same name you can find in `google-services.json` file. This name should identical.
Next, go to the `MainPage.xaml` and paste this code in VerticalStackLayout block:
```xml
<Image
                HeightRequest="200"
                HorizontalOptions="Center"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                Source="dotnet_bot.png" />

            <Label
                FontSize="32"
                HorizontalOptions="Center"
                SemanticProperties.HeadingLevel="Level1"
                Text="Hello, Firebase notifications" />

            <Label
                FontSize="18"
                HorizontalOptions="Center"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                SemanticProperties.HeadingLevel="Level2"
                Text="Welcome to .NET Multi-platform App UI" />

            <Button
                Clicked="GetTokenClicked"
                HorizontalOptions="Center"
                SemanticProperties.Hint="Get registration id token"
                Text="Get Token"
                x:Name="CounterBtn" />
```

After that, you should create an event handler like this:
```C#
private async void GetTokenClicked(object sender, EventArgs e)
	{
		await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
		var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
		Token = token;
		await DisplayAlert("FCM token", token, "OK");
	}
```

And don't forget to add a property for keeping token:
```C#
public string Token { get; set; }
```

The first part is ready. Let's check out it.


![main page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ejw0304k6qti66ohirty.png)


![got token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iv2h3w3baylvkd6hy34n.png)

We got a token that was registered in Firebase. Without this token, you can't send notifications.

##Implementing sending notifications
And now, we need to configure sending notifications.
Let's return to the Firebase console again and find gears. Select the "Project settings" and "Service accounts" tab. Click "Generate new private key."


![settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dlwpqujcvaflx64knl7k.png)

Save it to your project into `Resources/Raw` folder with name `firebase-adminsdk.json`.

After that return to `MainPage.xaml` and add the button:
```xml
<Button
                Clicked="SendPushClicked"
                HorizontalOptions="Center"
                SemanticProperties.Hint="Send notification"
                Text="Send push"
                x:Name="SendPush" />
```

Add handler to `MainPage.cs`. Here it loads the file sdk settings and creates an application that sends a notification:
```C#
private async void SendPushClicked(object sender, EventArgs e)
	{
		var app = FirebaseApp.Create(new AppOptions
		{
			Credential = await GetCredential()
		});
		
		FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);
		var message = new Message()
		{
			Token = Token,
			Notification = new Notification { Title = "Hello world!", Body = "It's a message for Android with MAUI"},
			Data = new Dictionary<string, string> {{"greating", "hello"}},
			Android = new AndroidConfig { Priority = Priority.Normal},
			Apns = new ApnsConfig { Headers = new Dictionary<string, string> { {"apns-priority", "5"}}}
		};
		var response = await messaging.SendAsync(message);
		await DisplayAlert("Response", response, "OK");
	}
	
	private async Task<GoogleCredential> GetCredential()
	{
		var path = await FileSystem.OpenAppPackageFileAsync("firebase-adminsdk.json");
		return GoogleCredential.FromStream(path);
	}
```

You'll see a lot of unresolved code, it means you need the `FirbaseAdminCore` package:
```bash
dotnet add package FirbaseAdminCore
```
After installing your code will resolved. And naw became time check out our application.


![main](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t9nynxx40uh5v6rcpr9f.png)

Getting token:

![token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obrebg90hmb1afgkpwfu.png)


Sending push:

![send](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hg94p5pdktpu6en0rt8.png)

Finally, we got the notification:

![push](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onagi31e0r9fdx4l93be.png)

##Conclusion.
It's an easy way to make notifications for mobile devices. Put likes on and subscribe. Happy coding!

Source code [here](https://github.com/SergKorol/PushMauiSample).

<a href="https://www.buymeacoffee.com/b9z99kntvtQ" target="_blank"><img src="http://dartfordwaffler.co.uk/wp-content/uploads/2021/03/buy-me-a-beer.jpg" alt="Buy Me A Beer" style="height: 60px !important;width: 317px !important;" ></a>