Xamarin.Forms Android receives notification, but ignores OnMessageReceived function

I'm working with push notifications on Xamarin.Forms and i want it to show the notification count in the Icon badge. I already made it work on iOS and found a plugin that does the work of show the badge on Android icon(XamarinShortcutBadger).
I implemented a FirebaseMessagingService class with an OnMessageReceived function to do the work of increment the icon badge number when a notification is received, but when i send the notification the output console shows an error -Error while parsing timestamp in GCM event- and nothing i use on the FirebaseMessagingService is apparently called, although the Notification did arives in the device.

using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Media;
using Android.Support.V4.App;
using Android.Util;
using Firebase.Messaging;
using XamarinShortcutBadger;

namespace MyApp.Droid
{

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    const string TAG = "MyFirebaseMsgService";
    int contador = 0;

    async public override void OnMessageReceived(RemoteMessage message)
    {
        var notification = message.GetNotification();
        var data = message.Data;
        string body = "";
        string title = "";
        if (data != null && data.ContainsKey("body") && data.ContainsKey("title"))
        {
            body = data["body"];
            title = data["title"];
        }
        else if (notification != null)
        {
            body = message.GetNotification().Body;
            title = message.GetNotification().Title;
        }

        if (!string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(title))
            SendNotification(body, title, message.Data);
            ShortcutBadger.ApplyCount(this, 1);

    }


    private void SendNotification(string title, string body, IDictionary<string, string> data)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }

        var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID).SetSmallIcon(Resource.Mipmap.icon_round).SetContentTitle(title).SetContentText(body).SetAutoCancel(true).SetContentIntent(pendingIntent);

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
        ShortcutBadger.ApplyCount(this, 2);

    }
}

}

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    Could you please post a basic demo so that we can test the code with it?

Sign In or Register to comment.