FCM in Xamarin.Forms - Control Notification in background

I have followed below example to implement FCM push notification in Xamarin Forms.

Due to restriction I could not post the article link. I would post it in comment section.

It explains 2 kind of notification handling -> 1, when app in background and 2, when app in foreground

In foreground case, one can control Notification by generating local notification.

Q1 - Is there a way we could control notification when in background and when app is closed status by generating local notification?
Q2 - Is it possible to control some action when user click on notification item like to redirect user to specific screen and display certain content etc ?

Answers

  • GuillaumePerrotGuillaumePerrot USMember ✭✭
    edited October 2017

    Q1) When the application is closed or in background, a notification is automatically generated by Firebase SDK, you don't have much control over that in the code except you can change default color, icon and android 8 channel identifier via meta-data (like shown in https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/AndroidManifest.xml#L11-L20). You can also of course control from the push payload itself: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support.

    Q2) Firebase UI to push does not have that. But if you use REST API to push, you can use the click_action notification field: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support. Click action must match an activity that has an intent filter with category default, and the action matching the string you push.

  • RaviKanasagraRaviKanasagra INMember ✭✭

    @Guillaume Perrot - Thank you for information. This helps. However, I find challenge to catch event when user clicks on this push notification on his device.

    I would appreciate if you could provide a code snippet to catch event when user clicks on this push notification in code for Xamarin Forms Android part.

  • RendyDelRosarioRendyDelRosario DOUniversity ✭✭✭

    Try using this plugin:

    https://github.com/CrossGeeks/FirebasePushNotificationPlugin

    Handles that seamless

  • RaviKanasagraRaviKanasagra INMember ✭✭

    Thank you @RendyDelRosario for this plugin.

    I did one POC using that plugin for Xamarin Forms Android part. I am able to receive notification on my mobile device however it did not fire event OnNotificationReceived provided by plugin.

    Also, when I click on notification message, it did not fire OnNotificationOpened event.

    I have added below code in App constructor.

    CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
                {
    
                    System.Diagnostics.Debug.WriteLine("Received");
    
                };
    
                CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
                {
                    System.Diagnostics.Debug.WriteLine("Opened");
                    foreach (var data in p.Data)
                    {
                        System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                    }
    
                    if (!string.IsNullOrEmpty(p.Identifier))
                    {
                        System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
                    }
    
                };
    

    I have a requirement to write some logic based on notification message click. Am I missing something?

  • RendyDelRosarioRendyDelRosario DOUniversity ✭✭✭
    edited October 2017

    @RaviKanasagra The events are triggered when you send data message, should not set notification messages if you want to use this event handlers. Just remove the notification part from your payload.

    Use this payload:

    {
                    "registration_ids": [
                          "eCMPWu62yOU:APA91bEb........."
                    ],
                    "data": {
                        "msg": "Hello FCM",
                        "title": "notification TITLE",
                        "body": "notification BODY",
                        "click_action" : "OPEN_ACTIVITY_1",
                        "other_key" : true
                    }
    
    
                }
    

    Check section: https://github.com/CrossGeeks/FirebasePushNotificationPlugin/blob/master/docs/FirebaseNotifications.md

  • RaviKanasagraRaviKanasagra INMember ✭✭

    Thank you for the info. Now, I am able to trigger events.

    But events are trigger multiple times on successive notification clicks. As these events are register every time I click on notification, it calls App class constructor using LoadApplication method in MainActivity in Xamarin.Android. I have tried removing registered event and then register again but still event called multiple times. :(

    I have register events in App class constructor as shown below.

                        CrossFirebasePushNotification.Current.OnTokenRefresh -= FCM_OnTokenRefresh;
                        CrossFirebasePushNotification.Current.OnTokenRefresh += FCM_OnTokenRefresh;
                        CrossFirebasePushNotification.Current.OnNotificationReceived -= FCM_OnNotificationReceived;
                        CrossFirebasePushNotification.Current.OnNotificationReceived += FCM_OnNotificationReceived;
                        CrossFirebasePushNotification.Current.OnNotificationOpened -= FCM_OnNotificationOpened;
                        CrossFirebasePushNotification.Current.OnNotificationOpened += FCM_OnNotificationOpened;
    
  • CeregolCeregol USMember ✭✭
    edited November 2017

    @RendyDelRosario quería comentar que seguí tu tutorial, y me funciona perfecto, es decir, recibo una notificación sin problema. Lo raro es que según este código debiera ver received en alguna parte. A pesar que llegan las notificaciones este método no funciona o no entra nunca. Tienes alguna solución ya que estoy implementando que cada vez que llegue una notificación cambie el icono de mi app.

       CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {
    
                System.Diagnostics.Debug.WriteLine("Received");
    
            };
    
  • RendyDelRosarioRendyDelRosario DOUniversity ✭✭✭

    @Ceregol

    Que payload estas enviando?

  • CeregolCeregol USMember ✭✭
    edited November 2017

    @RendyDelRosario la verdad no se bien que es "payload" , pero segun google seria que notificación o encabezado estoy utilizando .
    Te cuento que utilizo firebase y este es el codigo en un webservice en c# en donde envió mi notificación

                    string Server_Key = "AAAApYKXRw8:APA91bGm4FvAZxxxq";
    
                    string senderId = "710860556047";
    
                    // string TokenFB = "cVfegfXs1K8:APA91bHUHAxQQ1j9geVrcL65j2lIxxx61s";
    
                    WebRequest tRequest = WebRequest.Create("....fcm.googleapis.com/fcm/send");
                    tRequest.Method = "post";
                    tRequest.ContentType = "application/json";
                    var data = new
                    {
                        to = TokenFB,
                        priority = "high",
                        notification = new
                        {
                            body = tbody2,
                            title = ttitle2,
                            sound = "Enabled"
    
                        }
    
                    };
    
                    var serializer = new JavaScriptSerializer();
                    var json = serializer.Serialize(data);
                    Byte[] byteArray = Encoding.UTF8.GetBytes(json);
                    tRequest.Headers.Add(string.Format("Authorization: key={0}", Server_Key));
                    tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                    tRequest.ContentLength = byteArray.Length;
                    using (Stream dataStream = tRequest.GetRequestStream())
                    {
                        dataStream.Write(byteArray, 0, byteArray.Length);
                        using (WebResponse tResponse = tRequest.GetResponse())
                        {
                            using (Stream dataStreamResponse = tResponse.GetResponseStream())
                            {
                                using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                {
                                    String sResponseFromServer = tReader.ReadToEnd();
                                    string str = sResponseFromServer;
                                }
                            }
                        }
                    }
    

    ref: es.stackoverflow.com/questions/81118/envio-de-notifcaciones-desde-vs-c-usando-firebase

  • DenniroDenniro Member ✭✭

    Hi,
    I would like a confirmation about handle a push notification when the app is in background or closed.
    I managed to handle the notification when the app is in foreground by using the OnNotificationReceived method. But there is no way the OnNotificationReceived called when the app is in foreground or in background.
    Is that correct ? Or i have misunderstood it ?
    (By the way the push notification comes to the device with no issue. I just want to do extra things when it arrives.)
    Thank you!

Sign In or Register to comment.