1

I am using Azure Hubs to send notifications. I am able to receive the notification and it displays on the device when I pull down the notifications window. However, I do not see the notification display at the top of the screen as expected. I even "locked" the screen and it didn't display. I got the notification sound and my logs show I received it.

Screen showing received notification

My FirebaseMessageService:

using System;
using System.Linq;
using WindowsAzure.Messaging;
using Android.App;
using Android.Content;
using Android.Support.V4.App;
using Android.Util;
using Firebase.Messaging;
using IDEQ.AQI.Pages;

namespace IDEQ.AQI.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class FirebaseService : FirebaseMessagingService
    {
        const string Tag = "FirebaseMsgService";

        public override void OnNewToken(string token)
        {
            // NOTE: save token instance locally, or log if desired

            SendRegistrationToServer(token);
        }

        private void SendRegistrationToServer(string token)
        {
            try
            {
                var hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this);

                // register device with Azure Notification Hub using the token from FCM
                var registration = hub.Register(token, Constants.SubscriptionTags);

                // subscribe to the SubscriptionTags list with a simple template.
                var pnsHandle = registration.PNSHandle;
                var templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Constants.FCMTemplateBody, Constants.SubscriptionTags);
            }
            catch (Exception e)
            {
                Log.Error(Constants.DebugTag, $"Error registering device: {e.Message}");
            }
        }

        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);
            string messageBody;


            Log.Info(Tag, "From: " + message.From);

            if (message.GetNotification() != null)
            {
                Log.Info(Tag, "Notification Message Body: " + message.GetNotification().Body);
                messageBody = message.GetNotification().Body;
            }

            // NOTE: test messages sent via the Azure portal will be received here
            else
            {
                messageBody = message.Data.Values.First();
            }

            // convert the incoming message to a local notification
            SendLocalNotification(messageBody);

            // send the incoming message directly to the MainPage
            SendMessageToMainPage(messageBody);
        }

        private void SendLocalNotification(string body)
        {
            try
            {
                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                intent.PutExtra("message", body);

                var requestCode = new Random().Next();
                var pendingIntent = PendingIntent.GetActivity(this, requestCode, intent, PendingIntentFlags.OneShot);

                var notificationBuilder = new NotificationCompat.Builder(this, Constants.NotificationChannelId)
                    .SetContentTitle("IDEQ Alert")
                    .SetSmallIcon(Resource.Drawable.ic_launcher)
                    .SetContentText(body)
                    .SetAutoCancel(true)
                    .SetShowWhen(false)
                    .SetContentIntent(pendingIntent);

                var notificationManager = NotificationManagerCompat.From(this);
                notificationManager.Notify(0, notificationBuilder.Build());
            }
            catch (Exception e)
            {
                Log.Error(Tag, e.ToString());
            }
        }

        private void SendMessageToMainPage(string body)
        {
            (Xamarin.Forms.Application.Current.MainPage as MainPage)?.AddMessage(body);
        }
    }
}

//My main activity where I create the channel:

private void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channel = new NotificationChannel(Constants.NotificationChannelId, Constants.NotificationChannelName, NotificationImportance.Default)
    {
        Description = string.Empty
    };

    var notificationManager = (NotificationManager) GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
}
Chris Fry
  • 13
  • 1
  • 3

1 Answers1

1

Notification in your system tray will only be displayed if application is in background or turned off. If your application is running, your OnMessageRecieved method will get hit, however Android will not display notification in the system try. This is how life cycle of push notification works in Android. The only way u can display notification in system tray when application in in foreground is when you force Local Notification like you did in SendLocalNotification method.

Woj
  • 773
  • 4
  • 17
  • So if I kill the app in the emulator it should show up in the foreground? I hit the power button on the emulator. It shows the black screen as expected. I then sent a test notification and I got the sound but nothing shown on the emulator screen. – Chris Fry Jul 22 '20 at 15:32
  • In the system tray. Yes correct. When you look at your code in your FirebaseService at top you create new Intent. You basically tell Android that this app subscribes to push notifications. Once you receive push notification Android will handle it accordinly. If in forground hit OnMessageReceived, if Background or killed Display in System Tray and hit OnMessageReceived. It could be the emulator issue. Have you tried on phisical device? – Woj Jul 22 '20 at 15:35
  • I have not tried on a physical device but will do so. I will change emulators and see if that makes a difference. – Chris Fry Jul 22 '20 at 15:41
  • I was using a Nexus 5 emulator. I changed it to a Pixel and same result. I clicked the power button to make it a black screen. Sent test message and nothing popped up, but if I pull down, I see the message. – Chris Fry Jul 22 '20 at 16:20
  • It seems like emulator. Did it work on phisical device? – Woj Jul 23 '20 at 08:31
  • 1
    It was completely my ignorance on how Android notifications are displayed. I haven't had an android device in 8 years lol. Thanks for your help! – Chris Fry Jul 24 '20 at 16:19
  • Just wanted to check as I don't normally user Android devices either. When would you expect the notrifcation to display at the top of the screen as it does on iOS? All I ever get is straight into System tray and then only if app is backgrounded – Pat Long - Munkii Yebee Mar 25 '22 at 14:01