Receiving firebase FCM messages multiple times in Xamarin












0















I'm trying to integrate Firebase FCM into my app but i'm receiving messages
multiple times.



I send the messages trough a cloud function that triggers whenever a notice is added to the database like this:



import { DataSnapshot } from "firebase-functions/lib/providers/database";
import { EventContext } from "firebase-functions";
import * as admin from 'firebase-admin'
import { ResolvePromise } from "./misc";

export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
const uid = context.params.uid;
const noticeid = String(context.params.noticeid);

const notice = snapshot.val();

return admin.database().ref('device-tokens').child(uid).child('0')
.on('value', (data) => {
const token = data.val();

if (token === null) {
return ResolvePromise();
}

const title = String(notice['Title']);
const body = String(notice['Body']);

console.log("Title: " + title);
console.log("Body: " + body);

const payload: admin.messaging.Message = {
data: {
notice_id: noticeid,
title: title,
body: body
},
android: {
ttl: 0
},
token: token
};

return admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});

});
}


This works fine i retrieve the device token, send the message and i receive it in my app in my messaging service.



using System;
using Android.App;
using Android.Support.V4.App;
using Firebase.Messaging;
using Android.Util;
using Doshi.Xamarin.Abstractions.StaticData;
using Android.Content;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Android;
using Xamarin.Forms;
using Plugin.CurrentActivity;
using Acr.UserDialogs;
using Doshi.Xamarin.Core.Helpers;
using Doshi.Xamarin.Abstractions.Misc;
using Doshi.Xamarin.Android.Logic.Interfaces;
using Doshi.Xamarin.Android.Logic.Implementations;

namespace Doshi.Droid
{
[Service(Name = "com.doshi.droid.DoshiMessagingService")]
[IntentFilter(new {"com.google.firebase.MESSAGING_EVENT"})]
public class DoshiMessagingService : FirebaseMessagingService
{
INoticePresenter _noticePresenter = new DoshiNoticePresenter();

public override void OnMessageReceived(RemoteMessage message)
{
HandleNotice(message);
}

private void HandleNotice(RemoteMessage message)
{
int id = DateTime.Now.Millisecond;
//Create the hardware notice.
_noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
}
}


The problem occurs when i log out of my app and then login again the same notices i received earlier are received again. I use google authentication with firebase in my app and i remove the device token from the database when i log out and add the current token when i login again. Could this be the problem?



from what i can see in the firebase logs the cloud function is only executed once for each message so i'm guessing somethings wrong on the client side. I read on a other stackoverflow post that setting ttl to 0 would resolve this issue but it's not effecting anything what i can see.



Has anybody else run into this issue or have any idea of what i'm doing wrong?
I'm using the latest "stable" version of the Xamarin.Firebase.* nugets.










share|improve this question





























    0















    I'm trying to integrate Firebase FCM into my app but i'm receiving messages
    multiple times.



    I send the messages trough a cloud function that triggers whenever a notice is added to the database like this:



    import { DataSnapshot } from "firebase-functions/lib/providers/database";
    import { EventContext } from "firebase-functions";
    import * as admin from 'firebase-admin'
    import { ResolvePromise } from "./misc";

    export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
    const uid = context.params.uid;
    const noticeid = String(context.params.noticeid);

    const notice = snapshot.val();

    return admin.database().ref('device-tokens').child(uid).child('0')
    .on('value', (data) => {
    const token = data.val();

    if (token === null) {
    return ResolvePromise();
    }

    const title = String(notice['Title']);
    const body = String(notice['Body']);

    console.log("Title: " + title);
    console.log("Body: " + body);

    const payload: admin.messaging.Message = {
    data: {
    notice_id: noticeid,
    title: title,
    body: body
    },
    android: {
    ttl: 0
    },
    token: token
    };

    return admin.messaging().send(payload)
    .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
    })
    .catch((error) => {
    console.log('Error sending message:', error);
    });

    });
    }


    This works fine i retrieve the device token, send the message and i receive it in my app in my messaging service.



    using System;
    using Android.App;
    using Android.Support.V4.App;
    using Firebase.Messaging;
    using Android.Util;
    using Doshi.Xamarin.Abstractions.StaticData;
    using Android.Content;
    using System.Collections.Generic;
    using System.Text;
    using Newtonsoft.Json;
    using Android;
    using Xamarin.Forms;
    using Plugin.CurrentActivity;
    using Acr.UserDialogs;
    using Doshi.Xamarin.Core.Helpers;
    using Doshi.Xamarin.Abstractions.Misc;
    using Doshi.Xamarin.Android.Logic.Interfaces;
    using Doshi.Xamarin.Android.Logic.Implementations;

    namespace Doshi.Droid
    {
    [Service(Name = "com.doshi.droid.DoshiMessagingService")]
    [IntentFilter(new {"com.google.firebase.MESSAGING_EVENT"})]
    public class DoshiMessagingService : FirebaseMessagingService
    {
    INoticePresenter _noticePresenter = new DoshiNoticePresenter();

    public override void OnMessageReceived(RemoteMessage message)
    {
    HandleNotice(message);
    }

    private void HandleNotice(RemoteMessage message)
    {
    int id = DateTime.Now.Millisecond;
    //Create the hardware notice.
    _noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
    }
    }


    The problem occurs when i log out of my app and then login again the same notices i received earlier are received again. I use google authentication with firebase in my app and i remove the device token from the database when i log out and add the current token when i login again. Could this be the problem?



    from what i can see in the firebase logs the cloud function is only executed once for each message so i'm guessing somethings wrong on the client side. I read on a other stackoverflow post that setting ttl to 0 would resolve this issue but it's not effecting anything what i can see.



    Has anybody else run into this issue or have any idea of what i'm doing wrong?
    I'm using the latest "stable" version of the Xamarin.Firebase.* nugets.










    share|improve this question



























      0












      0








      0








      I'm trying to integrate Firebase FCM into my app but i'm receiving messages
      multiple times.



      I send the messages trough a cloud function that triggers whenever a notice is added to the database like this:



      import { DataSnapshot } from "firebase-functions/lib/providers/database";
      import { EventContext } from "firebase-functions";
      import * as admin from 'firebase-admin'
      import { ResolvePromise } from "./misc";

      export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
      const uid = context.params.uid;
      const noticeid = String(context.params.noticeid);

      const notice = snapshot.val();

      return admin.database().ref('device-tokens').child(uid).child('0')
      .on('value', (data) => {
      const token = data.val();

      if (token === null) {
      return ResolvePromise();
      }

      const title = String(notice['Title']);
      const body = String(notice['Body']);

      console.log("Title: " + title);
      console.log("Body: " + body);

      const payload: admin.messaging.Message = {
      data: {
      notice_id: noticeid,
      title: title,
      body: body
      },
      android: {
      ttl: 0
      },
      token: token
      };

      return admin.messaging().send(payload)
      .then((response) => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);
      })
      .catch((error) => {
      console.log('Error sending message:', error);
      });

      });
      }


      This works fine i retrieve the device token, send the message and i receive it in my app in my messaging service.



      using System;
      using Android.App;
      using Android.Support.V4.App;
      using Firebase.Messaging;
      using Android.Util;
      using Doshi.Xamarin.Abstractions.StaticData;
      using Android.Content;
      using System.Collections.Generic;
      using System.Text;
      using Newtonsoft.Json;
      using Android;
      using Xamarin.Forms;
      using Plugin.CurrentActivity;
      using Acr.UserDialogs;
      using Doshi.Xamarin.Core.Helpers;
      using Doshi.Xamarin.Abstractions.Misc;
      using Doshi.Xamarin.Android.Logic.Interfaces;
      using Doshi.Xamarin.Android.Logic.Implementations;

      namespace Doshi.Droid
      {
      [Service(Name = "com.doshi.droid.DoshiMessagingService")]
      [IntentFilter(new {"com.google.firebase.MESSAGING_EVENT"})]
      public class DoshiMessagingService : FirebaseMessagingService
      {
      INoticePresenter _noticePresenter = new DoshiNoticePresenter();

      public override void OnMessageReceived(RemoteMessage message)
      {
      HandleNotice(message);
      }

      private void HandleNotice(RemoteMessage message)
      {
      int id = DateTime.Now.Millisecond;
      //Create the hardware notice.
      _noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
      }
      }


      The problem occurs when i log out of my app and then login again the same notices i received earlier are received again. I use google authentication with firebase in my app and i remove the device token from the database when i log out and add the current token when i login again. Could this be the problem?



      from what i can see in the firebase logs the cloud function is only executed once for each message so i'm guessing somethings wrong on the client side. I read on a other stackoverflow post that setting ttl to 0 would resolve this issue but it's not effecting anything what i can see.



      Has anybody else run into this issue or have any idea of what i'm doing wrong?
      I'm using the latest "stable" version of the Xamarin.Firebase.* nugets.










      share|improve this question
















      I'm trying to integrate Firebase FCM into my app but i'm receiving messages
      multiple times.



      I send the messages trough a cloud function that triggers whenever a notice is added to the database like this:



      import { DataSnapshot } from "firebase-functions/lib/providers/database";
      import { EventContext } from "firebase-functions";
      import * as admin from 'firebase-admin'
      import { ResolvePromise } from "./misc";

      export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
      const uid = context.params.uid;
      const noticeid = String(context.params.noticeid);

      const notice = snapshot.val();

      return admin.database().ref('device-tokens').child(uid).child('0')
      .on('value', (data) => {
      const token = data.val();

      if (token === null) {
      return ResolvePromise();
      }

      const title = String(notice['Title']);
      const body = String(notice['Body']);

      console.log("Title: " + title);
      console.log("Body: " + body);

      const payload: admin.messaging.Message = {
      data: {
      notice_id: noticeid,
      title: title,
      body: body
      },
      android: {
      ttl: 0
      },
      token: token
      };

      return admin.messaging().send(payload)
      .then((response) => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);
      })
      .catch((error) => {
      console.log('Error sending message:', error);
      });

      });
      }


      This works fine i retrieve the device token, send the message and i receive it in my app in my messaging service.



      using System;
      using Android.App;
      using Android.Support.V4.App;
      using Firebase.Messaging;
      using Android.Util;
      using Doshi.Xamarin.Abstractions.StaticData;
      using Android.Content;
      using System.Collections.Generic;
      using System.Text;
      using Newtonsoft.Json;
      using Android;
      using Xamarin.Forms;
      using Plugin.CurrentActivity;
      using Acr.UserDialogs;
      using Doshi.Xamarin.Core.Helpers;
      using Doshi.Xamarin.Abstractions.Misc;
      using Doshi.Xamarin.Android.Logic.Interfaces;
      using Doshi.Xamarin.Android.Logic.Implementations;

      namespace Doshi.Droid
      {
      [Service(Name = "com.doshi.droid.DoshiMessagingService")]
      [IntentFilter(new {"com.google.firebase.MESSAGING_EVENT"})]
      public class DoshiMessagingService : FirebaseMessagingService
      {
      INoticePresenter _noticePresenter = new DoshiNoticePresenter();

      public override void OnMessageReceived(RemoteMessage message)
      {
      HandleNotice(message);
      }

      private void HandleNotice(RemoteMessage message)
      {
      int id = DateTime.Now.Millisecond;
      //Create the hardware notice.
      _noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
      }
      }


      The problem occurs when i log out of my app and then login again the same notices i received earlier are received again. I use google authentication with firebase in my app and i remove the device token from the database when i log out and add the current token when i login again. Could this be the problem?



      from what i can see in the firebase logs the cloud function is only executed once for each message so i'm guessing somethings wrong on the client side. I read on a other stackoverflow post that setting ttl to 0 would resolve this issue but it's not effecting anything what i can see.



      Has anybody else run into this issue or have any idea of what i'm doing wrong?
      I'm using the latest "stable" version of the Xamarin.Firebase.* nugets.







      c# android firebase xamarin firebase-cloud-messaging






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 14:49









      Frank van Puffelen

      241k29385413




      241k29385413










      asked Nov 25 '18 at 14:05









      scottyaimscottyaim

      2114




      2114
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468297%2freceiving-firebase-fcm-messages-multiple-times-in-xamarin%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens






            share|improve this answer




























              0














              Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens






              share|improve this answer


























                0












                0








                0







                Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens






                share|improve this answer













                Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 15:31









                scottyaimscottyaim

                2114




                2114
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468297%2freceiving-firebase-fcm-messages-multiple-times-in-xamarin%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Wiesbaden

                    Marschland

                    Dieringhausen