locked
How to add Firebase Cloud Messaging to Xamarin.Forms app? RRS feed

  • Question

  • User42185 posted

    Google has replaced GCM with the new FCM for push notifications. I am trying to implement push notifications in my Android (Xamarin.Forms) project. It appears that FCM is not yet supported for Forms due to Google Play Services dependency issues. When I attempt to implement using the old GCM system, the Google Developer Console will not allow me access the GCM API credentials page (just redirects me to FCM). Does anyone have any suggestions to get push notifications working with Android in a Xamarin.Forms solution? Note: I am using Azure Notification Hub to send the messages (I have iOS already working)

    Monday, November 28, 2016 5:22 PM

Answers

  • User78468 posted

    @wolfprogrammer @MCvel I was able to use FCM when changed to V32.940.0-beta3 while I wait for a new release on XF

    It's working perfectly so far

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, December 8, 2016 9:26 AM

All replies

  • User154141 posted

    I am exactly in the same situation as you are, cannot create a GCM api now, and no FCM support yet for Xamarin Android, or if anybody knows if there is a workaround for this, would be extremely helpful,

    thank you all!

    Wednesday, December 7, 2016 8:18 PM
  • User154141 posted

    I guess I was searching wrongly, found this, https://developer.xamarin.com/guides/android/application_fundamentals/notifications/remote-notifications-with-fcm/

    I'll tell my results in a while

    Wednesday, December 7, 2016 9:54 PM
  • User42185 posted

    @MCvel the issue I am having is an incompatibility with Xamarin.Forms not Xamarin.Android.

    The latest Xamarin.Forms package is dependent on Xamarin.Android.Support.v4 (23.3.0). Xamarin.Firebase.Messaging is dependent on Xamarin.GooglePlayServices.Basement (32.961.0). Xamarin.GooglePlayServices.Basement (32.961.0) is dependent on Xamarin.Android.Support.v4 (>=24.2.1)

    Wednesday, December 7, 2016 9:57 PM
  • User154141 posted

    I'm facing the same, will work on this, I'll let you know, in the meantime, something that help me in the past for this kind of references issues

    https://forums.xamarin.com/discussion/comment/169816/#Comment_169816

    regards

    Wednesday, December 7, 2016 10:54 PM
  • User78468 posted

    @wolfprogrammer @MCvel I was able to use FCM when changed to V32.940.0-beta3 while I wait for a new release on XF

    It's working perfectly so far

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, December 8, 2016 9:26 AM
  • User154141 posted

    thanks @PedroCosta that actually works, however I still stuck in the nuget dependency hell, since I'm also using Xamarin.Forms.Maps on my app and its later version has this restriction

    Xamarin.GooglePlayServices.Maps (= 29.0.0.1)

    do you know if there's a way to make FCM without that specific library?, maybe using GCM and stuff, sighs

    thank you!!

    Thursday, December 8, 2016 6:36 PM
  • User180464 posted

    same issues for me, waiting for xamarin to release a newer version that not depends on the old 23.3.0 version...

    Thursday, December 8, 2016 7:44 PM
  • User154141 posted

    Finally!! I am receiving push notifications, I used the AWS SDK instead any other library, following this tutorial

    http://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/getting-started-sns-android.html

    Thursday, December 8, 2016 10:23 PM
  • User78468 posted

    @MCvel I almost changed to another library also

    Friday, December 9, 2016 3:41 AM
  • User251799 posted

    @MCvel said: Finally!! I am receiving push notifications, I used the AWS SDK instead any other library, following this tutorial

    http://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/getting-started-sns-android.html

    @MCvel Do you mind posting the relevant snippets? That would be awesome!

    Saturday, December 24, 2016 12:42 AM
  • User154141 posted

    well there are some steps that needs to be followed,

    1. For Android you need to enable the Firebase Cloud Messaging FCM (the new GCM) https://firebase.google.com/docs/cloud-messaging/
    2. iOS you need to create and enable aPNS in your app, something like this (https://support.magplus.com/hc/en-us/articles/203808718-iOS-Creating-a-Push-Notification-Certificate)
    3. In AWS, you need to enable and configure SNS in order to send notifications http://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/sns-send-push-notifications-android.html
    4. Now, in Xamarin you need to get the Device Token for each (Android and iOS)

    in iOS, you can add this in the AppDelegate

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) { // Modify device token for compatibility Azure var token = deviceToken.Description; token = token.Trim('<', '>').Replace(" ", ""); }

    and then override the ReceivedRemoteNotification to handle the push notification message.

    `public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo) { NSObject inAppMessage;

                var success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);
    
                if (success)
                {
                    var alert = new UIAlertView("Notification!", inAppMessage.ToString(), null, "OK", null);
                    alert.Show();
                }
    

    }`

    Now, in Android in the MainActivity add this method:

    private void RegisterForGCM() { string senders = AwsConfigValues.GCM_SENDER; Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER"); intent.SetPackage("com.google.android.gsf"); intent.PutExtra("app", PendingIntent.GetBroadcast(this, 0, new Intent(), 0)); intent.PutExtra("sender", senders); StartService(intent); }

    then you can create and configure the Service, where you are going to get the token and configure: - GCMIntentService.cs

    `namespace MyApp.Droid { [Service] public class GCMIntentService : IntentService { static PowerManager.WakeLock sWakeLock; static object LOCK = new object();

        public static void RunIntentInService(Context context, Intent intent)
        {
            lock (LOCK)
            {
                if (sWakeLock == null)
                {
                    // This is called from BroadcastReceiver, there is no init.
                    var pm = PowerManager.FromContext(context);
                    sWakeLock = pm.NewWakeLock(
                    WakeLockFlags.Partial, "My WakeLock Tag");
                }
            }
    
            sWakeLock.Acquire();
            intent.SetClass(context, typeof(GCMIntentService));
            context.StartService(intent);
        }
    
        protected override void OnHandleIntent(Intent intent)
        {
            try
            {
                Context context = this.ApplicationContext;
                string action = intent.Action;
    
                if (action.Equals("com.google.android.c2dm.intent.REGISTRATION"))
                {
                    HandleRegistration(intent);
                }
                else if (action.Equals("com.google.android.c2dm.intent.RECEIVE"))
                {
                    HandleMessage(intent);
                }
            }
            finally
            {
                lock (LOCK)
                {
                    //Sanity check for null as this is a public method
                    if (sWakeLock != null)
                        sWakeLock.Release();
                }
            }
        }
    
        private void HandleRegistration(Intent intent)
        {
            //Get you Android Device Token Here <<<<
            AppConstants.TOKEN_ANDROID = intent.GetStringExtra("registration_id");
        }
    
        private void HandleMessage(Intent intent)
        {
            string message = string.Empty;
            Bundle extras = intent.Extras;
            if (!string.IsNullOrEmpty(extras.GetString("message")))
            {
                message = extras.GetString("message");
            }
            else
            {
                message = extras.GetString("default");
            }
    
            Log.Info("Messages", "message received = " + message);
    
            AndroidUtils.ShowNotification(this, "MyAppTitle", message);
    
            //show the message
    
        }
    }
    

    }`

    also add a class to create a BroadcastReceiver, add a new class: - GNCBroadcastReceiver

    `namespace MyApp.Droid { [BroadcastReceiver(Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter(new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "com.amazonaws.sns" })] [IntentFilter(new string[] { "com.google.android.c2dm.intent.REGISTRATION" }, Categories = new string[] { "com.amazonaws.sns" })] [IntentFilter(new string[] { "com.google.android.gcm.intent.RETRY" }, Categories = new string[] { "com.amazonaws.sns" })] public class GCMBroadcastReceiver : BroadcastReceiver { const string TAG = "PushHandlerBroadcastReceiver"; public override void OnReceive(Context context, Intent intent) { GCMIntentService.RunIntentInService(context, intent); SetResult(Result.Ok, null, null); } }

    [BroadcastReceiver]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    public class GCMBootReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            GCMIntentService.RunIntentInService(context, intent);
            SetResult(Result.Ok, null, null);
        }
    }
    

    }`

    Once you get the device tokens, you need to register them in the SNS then create an EndPoint and send the notifications, you can also follow some tutorials in AWS http://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/sns-send-push-notifications-android.html, also this blog was helpful to me https://blog.verslu.is/xamarin/xamarin-forms-xamarin/push-notifications-with-xamarin-introduction/

    regards,

    Tuesday, December 27, 2016 6:15 AM
  • User275591 posted

    SNS actually use GCM, it doesn't use firebase for android

    Thursday, December 29, 2016 11:59 AM
  • User228975 posted

    Hi,

    Does anyone know how to get around the Firebase Token returning the same value on the subsequent build of release. This release is not the app store release but a deployment of release build to a physical phone for testing.

    On a fresh/first time deploy of the app, the token value works with FCM. The problem arise with FCM returning error where sending a message to the device will result in a "unregistered registration token" on the subsequent build and deploy.

    I know that some suggest to use the #if DEBUG but the release build is not in debug mode. One reason that I cannot use Debug build is that I have "remote service" [Service(Name = "com.myapp.service", Enabled = true, Process = ":bgservice")] process which does not work in debug mode (will 200% crash the service on startup).

    Wednesday, April 26, 2017 7:43 AM