Xamarin Android通知未在前景中显示

时间:2020-07-22 15:16:21

标签: android xamarin push-notification

我正在使用Azure集线器发送通知。我能够接收到通知,并且在下拉通知窗口时它会显示在设备上。但是,我没有按预期在屏幕顶部看到通知显示。我什至“锁定”了屏幕,但没有显示。我收到通知声音,并且日志显示我收到了通知。

Screen showing received notification

我的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);
}

1 个答案:

答案 0 :(得分:0)

仅当应用程序处于后台或关闭状态时,才会显示系统托盘中的通知。如果您的应用程序正在运行,您的OnMessageRecieved方法将被命中,但是Android不会在系统尝试中显示通知。这是推送通知的生命周期在Android中的工作方式。 当应用程序在前台运行时,您可以像在SendLocalNotification方法中那样强制执行本地通知时,您只能在系统任务栏中显示通知。