How to Implement FCM in Xamarin Forms

HabibAli_SubhanHabibAli_Subhan PKMember ✭✭
edited March 2017 in Xamarin.Forms

So many people have asked for convenient and efficient way of implementing FCM (Firebase Cloud Messaging) for android in Xamarin Form. Actually FCM lib cannot be installed in xamarin forms due to version conflict of android support lib present in xamarin forms. So here is the work around

Firebase Cloud Messaging (FCM) is a cross-platform service that handles the sending, routing, and queueing of messages between server applications and mobile client apps. FCM is the successor to Google Cloud Messaging (GCM), and it is built on Google Play Services.

Refer to following sample project in which the FCM is implemented in xamarin forms

https://github.com/HabibAli/FCM-Xamarin-Forms

If you want a similar implementation in your project then copy the GCM.Client folder in your project

In MainActivity.cs class declare

using Gcm.Client; at the top

and in class body

static MainActivity instance = null;

// Return the current activity instance.
    public static MainActivity CurrentActivity
    {
      get
      {
        return instance;
      }
    }

In OnCreate method

base.OnCreate(bundle);

try
{
  // Check to ensure everything's set up right
  GcmClient.CheckDevice(this);
  GcmClient.CheckManifest(this);

  // Register for push notifications
  System.Diagnostics.Debug.WriteLine("Registering...");
  GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
}
catch (Java.Net.MalformedURLException)
{
  CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
}
catch (Exception e)
{
  CreateAndShowDialog(e.Message, "Error");
}

Declare the function

    private void CreateAndShowDialog(String message, String title)
    {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);

      builder.SetMessage(message);
      builder.SetTitle(title);
      builder.Create().Show();
    }

Your app needs to import Gcm.Client folder into the project
In that folder following classes are present

Constants.cs //Constants for GCM. In that file you also need to provide SENDER_ID as derived from your firebase console application
https://console.firebase.google.com/
GcmBroadcastReceiverBase.cs //Receiver for push notification
GcmService.cs //A service for registering and receiving notification
GcmServiceBase.cs //Base class
InternalGcmClient.cs //Utility class for GCM Client

Following nuggets needs to be present in your application

Xamarin.Android.Support.v7.AppCompat 23.3.0
Xamarin.GooglePlayServices.Gcm 29.0.0.2

After doing all those tasks above, your project is ready to process push notification fired by firebase console

Regards

Habib Ali
Mohammad Samiullah Farooqi

Posts

  • LukaszWroblewskiLukaszWroblewski USMember ✭✭
    edited March 2017
    Thanks, that is useful.
    But you're not showing how to use FCM on the client app, but just the old GCM.
    One of the main new feature of FCM is to get rid of the registration id process (on boot, on start, on app update, ...). But you have to keep registering to GCM in your exemple.
  • Thanks for the example. Very handy implementation but I am wondering, the click of the notification, a specific view with the notifications content appears?

  • HabibAli_SubhanHabibAli_Subhan PKMember ✭✭

    @LukaszWroblewski said:
    Thanks, that is useful.
    But you're not showing how to use FCM on the client app, but just the old GCM.
    One of the main new feature of FCM is to get rid of the registration id process (on boot, on start, on app update, ...). But you have to keep registering to GCM in your exemple.

    Actually FCM itself is a wrapper on GCM. By implementing FCM here is make sure that you use FCM console or FCM sdk via server to send push notifications

  • HabibAli_SubhanHabibAli_Subhan PKMember ✭✭

    @PatrickFlaherty.2619 said:
    Thanks for the example. Very handy implementation but I am wondering, the click of the notification, a specific view with the notifications content appears?

    Thanks. You can implement your own activity intent when receive the notification in GcmService.cs

  • HabibAli.7513HabibAli.7513 USMember

    One thing I forgot to mention that in OnCreate method of MainActivity, you also need to write

    instance = this;

  • @HabibAli_Subhan said:

    @PatrickFlaherty.2619 said:
    Thanks for the example. Very handy implementation but I am wondering, the click of the notification, a specific view with the notifications content appears?

    Thanks. You can implement your own activity intent when receive the notification in GcmService.cs

    @HabibAli_Subhan said:
    So many people have asked for convenient and efficient way of implementing FCM (Firebase Cloud Messaging) for android in Xamarin Form. Actually FCM lib cannot be installed in xamarin forms due to version conflict of android support lib present in xamarin forms. So here is the work around

    Firebase Cloud Messaging (FCM) is a cross-platform service that handles the sending, routing, and queueing of messages between server applications and mobile client apps. FCM is the successor to Google Cloud Messaging (GCM), and it is built on Google Play Services.

    Refer to following sample project in which the FCM is implemented in xamarin forms

    https://github.com/HabibAli/FCM-Xamarin-Forms

    If you want a similar implementation in your project then copy the GCM.Client folder in your project

    In MainActivity.cs class declare

    using Gcm.Client; at the top

    and in class body

    static MainActivity instance = null;
    
    // Return the current activity instance.
        public static MainActivity CurrentActivity
        {
          get
          {
            return instance;
          }
        }
    

    In OnCreate method

    base.OnCreate(bundle);
    
    try
    {
      // Check to ensure everything's set up right
      GcmClient.CheckDevice(this);
      GcmClient.CheckManifest(this);
    
      // Register for push notifications
      System.Diagnostics.Debug.WriteLine("Registering...");
      GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
    }
    catch (Java.Net.MalformedURLException)
    {
      CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
    }
    catch (Exception e)
    {
      CreateAndShowDialog(e.Message, "Error");
    }
    

    Declare the function

        private void CreateAndShowDialog(String message, String title)
        {
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
          builder.SetMessage(message);
          builder.SetTitle(title);
          builder.Create().Show();
        }
    

    Your app needs to import Gcm.Client folder into the project
    In that folder following classes are present

    Constants.cs //Constants for GCM. In that file you also need to provide SENDER_ID as derived from your firebase console application
    https://console.firebase.google.com/
    GcmBroadcastReceiverBase.cs //Receiver for push notification
    GcmService.cs //A service for registering and receiving notification
    GcmServiceBase.cs //Base class
    InternalGcmClient.cs //Utility class for GCM Client

    Following nuggets needs to be present in your application

    Xamarin.Android.Support.v7.AppCompat 23.3.0
    Xamarin.GooglePlayServices.Gcm 29.0.0.2

    After doing all those tasks above, your project is ready to process push notification fired by firebase console

    Regards

    Habib Ali
    Mohammad Samiullah Farooqi

    @HabibAli_Subhan It seem that i need to upload an apple certificate, should i have it ? just to test , to get an apple certificate , it has to be enrrolled in the 99 dolars apple developer plan

  • HabibAli_SubhanHabibAli_Subhan PKMember ✭✭

    Yes you need to have the developer portal access (99$ per year) to make the APNS certificate and for its prerequisites

  • LuanSantiagoLuanSantiago USMember ✭✭

    @HabibAli_Subhan said:
    So many people have asked for convenient and efficient way of implementing FCM (Firebase Cloud Messaging) for android in Xamarin Form. Actually FCM lib cannot be installed in xamarin forms due to version conflict of android support lib present in xamarin forms. So here is the work around

    Firebase Cloud Messaging (FCM) is a cross-platform service that handles the sending, routing, and queueing of messages between server applications and mobile client apps. FCM is the successor to Google Cloud Messaging (GCM), and it is built on Google Play Services.

    Refer to following sample project in which the FCM is implemented in xamarin forms

    https://github.com/HabibAli/FCM-Xamarin-Forms

    If you want a similar implementation in your project then copy the GCM.Client folder in your project

    In MainActivity.cs class declare

    using Gcm.Client; at the top

    and in class body

    static MainActivity instance = null;
    
    // Return the current activity instance.
        public static MainActivity CurrentActivity
        {
          get
          {
            return instance;
          }
        }
    

    In OnCreate method

    base.OnCreate(bundle);
    
    try
    {
      // Check to ensure everything's set up right
      GcmClient.CheckDevice(this);
      GcmClient.CheckManifest(this);
    
      // Register for push notifications
      System.Diagnostics.Debug.WriteLine("Registering...");
      GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
    }
    catch (Java.Net.MalformedURLException)
    {
      CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
    }
    catch (Exception e)
    {
      CreateAndShowDialog(e.Message, "Error");
    }
    

    Declare the function

        private void CreateAndShowDialog(String message, String title)
        {
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
          builder.SetMessage(message);
          builder.SetTitle(title);
          builder.Create().Show();
        }
    

    Your app needs to import Gcm.Client folder into the project
    In that folder following classes are present

    Constants.cs //Constants for GCM. In that file you also need to provide SENDER_ID as derived from your firebase console application
    https://console.firebase.google.com/
    GcmBroadcastReceiverBase.cs //Receiver for push notification
    GcmService.cs //A service for registering and receiving notification
    GcmServiceBase.cs //Base class
    InternalGcmClient.cs //Utility class for GCM Client

    Following nuggets needs to be present in your application

    Xamarin.Android.Support.v7.AppCompat 23.3.0
    Xamarin.GooglePlayServices.Gcm 29.0.0.2

    After doing all those tasks above, your project is ready to process push notification fired by firebase console

    Regards

    Habib Ali
    Mohammad Samiullah Farooqi

    @HabibAli_Subhan said:
    So many people have asked for convenient and efficient way of implementing FCM (Firebase Cloud Messaging) for android in Xamarin Form. Actually FCM lib cannot be installed in xamarin forms due to version conflict of android support lib present in xamarin forms. So here is the work around

    Firebase Cloud Messaging (FCM) is a cross-platform service that handles the sending, routing, and queueing of messages between server applications and mobile client apps. FCM is the successor to Google Cloud Messaging (GCM), and it is built on Google Play Services.

    Refer to following sample project in which the FCM is implemented in xamarin forms

    https://github.com/HabibAli/FCM-Xamarin-Forms

    If you want a similar implementation in your project then copy the GCM.Client folder in your project

    In MainActivity.cs class declare

    using Gcm.Client; at the top

    and in class body

    static MainActivity instance = null;
    
    // Return the current activity instance.
        public static MainActivity CurrentActivity
        {
          get
          {
            return instance;
          }
        }
    

    In OnCreate method

    base.OnCreate(bundle);
    
    try
    {
      // Check to ensure everything's set up right
      GcmClient.CheckDevice(this);
      GcmClient.CheckManifest(this);
    
      // Register for push notifications
      System.Diagnostics.Debug.WriteLine("Registering...");
      GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
    }
    catch (Java.Net.MalformedURLException)
    {
      CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
    }
    catch (Exception e)
    {
      CreateAndShowDialog(e.Message, "Error");
    }
    

    Declare the function

        private void CreateAndShowDialog(String message, String title)
        {
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
          builder.SetMessage(message);
          builder.SetTitle(title);
          builder.Create().Show();
        }
    

    Your app needs to import Gcm.Client folder into the project
    In that folder following classes are present

    Constants.cs //Constants for GCM. In that file you also need to provide SENDER_ID as derived from your firebase console application
    https://console.firebase.google.com/
    GcmBroadcastReceiverBase.cs //Receiver for push notification
    GcmService.cs //A service for registering and receiving notification
    GcmServiceBase.cs //Base class
    InternalGcmClient.cs //Utility class for GCM Client

    Following nuggets needs to be present in your application

    Xamarin.Android.Support.v7.AppCompat 23.3.0
    Xamarin.GooglePlayServices.Gcm 29.0.0.2

    After doing all those tasks above, your project is ready to process push notification fired by firebase console

    Regards

    Habib Ali
    Mohammad Samiullah Farooqi

    I get the token, but my services are never called to receive the notifications, any solution?

  • JosecanallaJosecanalla ARMember ✭✭
    edited May 2017

    Hello, I downloaded and installed your solution. Only I change the SENDER_ID and try to send messages via Firebase Cloud Messaging Console. My smartphone receives the messages correctly, but the text are incorrect. I get this in msg var of "OnMessage" method of GcmService.cs

    {google.c.a.c_l=MyLabel
    google.c.a.udt=0
    google.sent_time=...
    gcm.notification.e=1
    google.c.a.c_id=...
    google.c.a.ts=...
    gcm.n.e=1
    from=....
    google.message_id=...
    gcm.notification.body=MyText
    google.c.a.e=1
    collapse_key=com.fcm.sample
    }

    where the text I set is MyText and label is MyLabel. (Where I put ... I have my sender_id, etc...)

    So in my smartphone I see "Unknown message details" and the text I pasted below.

    Thanks!

  • JosecanallaJosecanalla ARMember ✭✭

    I solved it setting
    string message = intent.Extras.GetString("gcm.notification.body");
    to get text of the notification.

  • 3pa23pa2 USMember ✭✭

    How to suscribe my app a topic?

  • madhav.shenoy83madhav.shenoy83 AUMember ✭✭

    I think this issue with version conflict no longer exists. I've written an answer in Stack Overflow, which shows how FCM can be implemented in Xamarin Forms. I've tested this successfully for Android, and will be updating the answer once I've tested iOS

  • RendyDelRosarioRendyDelRosario DOUniversity ✭✭✭

    Just released this plugin:

    https://www.nuget.org/packages/Plugin.FirebasePushNotification

    Might be helpful

  • Implement your solution in my project and since a few days when I send notifications from firebase console do not reach my client application, is there any new FCM update for GCM because scontinuan not working notifications do not arrive when sending from firebase console also download your Project and do you have any suggestions ???

  • How can I receive a message on android boot? I could start the GcmService but can't do the registration! It only work if i start the application.

  • pnet1pnet1 USMember ✭✭✭✭
    edited September 2017

    @HabibAli_Subhan, a question: If do i implement for android using xam.forms only, i need to pay $99 per year or not?

    I went run your project downloaded from your git and i tried to compile, i get it this error:

    Falha inesperada da tarefa "ResolveLibraryProjectImports".
    System.IO.FileNotFoundException: Could not load assembly 'FCM, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
    Nome do arquivo: 'FCM.dll'
    em Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
    em Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName, ReaderParameters parameters)
    em Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
    em Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.GetAssembly(String fileName)
    em Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection1 jars, ICollection1 resolvedResourceDirectories, ICollection1 resolvedAssetDirectories, ICollection1 resolvedEnvironments)
    em Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
    em Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
    em Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() FCM.Droid

  • pnet1pnet1 USMember ✭✭✭✭

    I'm having problem with this DLL:

    Xamarin.Forms.Build.Tasks.dll.

    There is in the folder, but fire an error of not instanced. How can i solve this?

  • pnet1pnet1 USMember ✭✭✭✭

    I got it to run FCM project. Now, how can i do to send message for it?

  • pnet1pnet1 USMember ✭✭✭✭

    Now, i went to run and fire a exception. I didn't understand. Before worked and now nothing. What's happened?

  • pnet1pnet1 USMember ✭✭✭✭
    edited September 2017

    I got it run my App, but i don't receiving message. From firebase i fire one message, but i don't receive in may App. I f i use the console program(server side) fires an error: InvalidRegistration. Anybody or @HabibAli_Subhan knows how can i solve this?

  • WindyhenWindyhen USMember ✭✭

    @RendyDelRosario said:
    Just released this plugin:

    https://www.nuget.org/packages/Plugin.FirebasePushNotification

    Might be helpful

    @RendyDelRosario im getting [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented

    On android all fine, im using iOS 11.1

    Any thoughts?

Sign In or Register to comment.