Xamarin Android - Google Firebase Cloud Messaging (FCM)

Introduction

FCM refers to Firebase Cloud Messaging. It’s used to send the message between the mobile apps and the Server Applications. For more details, refer refer here

Let’s start

Before starting our Android Application creation, we need to register Google Firebase Console New Project.

Step 1

Go to https://console.firebase.google.com/ Check the page center, which has +Add Project. Now click the button and open one more Window for Create New Project. It asks Project Name and Country. Click the button Create Project and afterwards it will create a new Project.

Step 2

Go to Overview-> Notification-> Get Started. Afterwards, open the new page, which will show what platform we need to create FCM option for ( iOS or an Android). Here, we will select an Android platform.

Step 3

Afterwards, select the platform for an Android and give the Android Package name, App Nick Name and Debug Singing Certificate (SHA-1). You need to create SHA-1 key by the link http://www.c-sharpcorner.com/article/xamarin-android-create-an-sha-1-key-for-google-map-app-deve/

Step 4

Afterwards, continue to Register the app. Go to the next step for Config Page. Here, we need to download google-services.json file. Afterwards, click Continue button.

Step 5

Open Visual Studio-> New Project->Templates-> Visual C#-> Android-> Blank App.

Select Blank App. Give the project name and the project location.

Step 6

Go to Solution Explorer-> Project Name-> References. Right click to Manage NuGet Packages, followed by opening new dialog box. This dialog box is required to search Xamarin Firebase, followed by installing Install Xamarin.Firebase.Messaging Packages.

Step 7

Goto Solution Explorer-> Project Name. Here, download Google-services.json file, copy and paste it nside the package. After pasting the file, close the Application.

Step 8

Go to Project Source folder, find the ProjectName.csproj file. Open and edit to add the code given below for Google-services.json config.

XML Code

  1. <ItemGroup>  
  2.    <GoogleServicesJson Include="google-services.json" />  
  3. </ItemGroup>  

Step 9

We need to add one class for FCM Token Creation. Go to Solution Explorer-> Project Name, followed by right clicking Add. Open the new dialog box. Select Class and give the name for MyFirebaseIIDService.cs. Add New Class.

Step 10

We need to add one Messaging receiving class. Go to Solution Explorer-> Project Name, followed by right clicking Add. Oen the new dialog box and select Class. Give the name for MyFireMessagingService.cs. Afterwards add New Class.

Step 11

Open Solution Explorer-> Project Name-> MyFirebaseIIDService.cs. Click Open CS code and Page view. Add the namespaces and C# Code given below. 

C# code 

  1. using Firebase.Iid;  
  2. using Android.Util;  
  3. namespace FCM {  
  4.     [Service]  
  5.     [IntentFilter(new [] {  
  6.         "com.google.firebase.INSTANCE_ID_EVENT"  
  7.     })]  
  8.     class MyFirebaseIIDService: FirebaseInstanceIdService {  
  9.         const string TAG = "MyFirebaseIIDService";  
  10.         public override void OnTokenRefresh() {  
  11.             var refreshedToken = FirebaseInstanceId.Instance.Token;  
  12.             Log.Debug(TAG, "Refreshed token: " + refreshedToken);  
  13.             SendRegistrationToServer(refreshedToken);  
  14.         }  
  15.         void SendRegistrationToServer(string token) {}  
  16.     }  
  17. }   

Step 12

Open Solution Explorer-> Project Name-> MyFireMessagingService.cs. Click Open CS code page view, followed by adding namespaces and C# Code given below.This class helps to receive messaging from FCM.

C# code

  1. using Firebase.Messaging;  
  2. using Android.Graphics;  
  3. namespace FCM {  
  4.     [Service]  
  5.     [IntentFilter(new [] {  
  6.         "com.google.firebase.MESSAGING_EVENT"  
  7.     })]  
  8.     class MyFireMessagingService: FirebaseMessagingService {  
  9.         public override void OnMessageReceived(RemoteMessage message) {  
  10.             base.OnMessageReceived(message);  
  11.             SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);  
  12.         }  
  13.         public void SendNotificatios(string body, string Header) {  
  14.             Notification.Builder builder = new Notification.Builder(this);  
  15.             builder.SetSmallIcon(Resource.Drawable.Icon);  
  16.             var intent = new Intent(thistypeof(MainActivity));  
  17.             intent.AddFlags(ActivityFlags.ClearTop);  
  18.             PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);  
  19.             builder.SetContentIntent(pendingIntent);  
  20.             builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon));  
  21.             builder.SetContentTitle(Header);  
  22.             builder.SetContentText(body);  
  23.             builder.SetDefaults(NotificationDefaults.Sound);  
  24.             builder.SetAutoCancel(true);  
  25.             NotificationManager notificationManager = (NotificationManager) GetSystemService(NotificationService);  
  26.             notificationManager.Notify(1, builder.Build());  
  27.         }  
  28.     }  
  29. }  

Step 13

Open Solution Explorer-> Project Name-> MainActivity.cs Click Open CS code Page view, followed by adding namespaces and C# Code given below. We created Temporary FCM Token for Single Device Notifications.

C# code

Namespace
  1. using System.Threading.Tasks;  
  2. using Firebase.Iid;  
  3. using Android.Util;  
  4. MainActivity.cs: -Task.Run(() => {  
  5.     var instanceid = FirebaseInstanceId.Instance;  
  6.     instanceid.DeleteInstanceId();  
  7.     Log.Debug("TAG""{0} {1}", instanceid.Token, instanceid.GetToken(this.GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));  
  8. });  

Step 14

Click select Solution Explorer->Project Name->Properties-> AndroidManifest.xml file.

XML Code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.fcm.fcm" android:versionCode="1" android:versionName="1.0">  
  3.     <uses-sdk android:minSdkVersion="16" />  
  4.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  5.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  6.     <uses-permission android:name="android.permission.WAKE_LOCK" />  
  7.     <application android:label="FCM">  
  8.         <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />  
  9.         <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:enabled="true" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">  
  10.             <intent-filter>  
  11.                 <action android:name="com.google.android.c2dm.intent.RECEIVE" />  
  12.                 <action android:name="com.google.android.c2dm.intent.REGISTRATION" />  
  13.                 <category android:name="${applicationId}" /> </intent-filter>  
  14.         </receiver>  
  15.     </application>  
  16. </manifest>  

Step 15

Click F5 or build and run the Application. Here, it is MainActivity.cs. After runnig the project, just copy the FCM Token, followed by directly going to Firebase Console, which has put the token followed by the images.



Step 16 

Finally Firebase Messaging output is given.

Finally, we successfully created Xamarin Android Application with Firebase Cloud Messaging.


Similar Articles