Xamarin Android 通知未显示在前台 [英] Xamarin Android Notification not Showing in Foreground

查看:67
本文介绍了Xamarin Android 通知未显示在前台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Azure 中心发送通知.当我拉下通知窗口时,我能够收到通知并显示在设备上.但是,我没有按预期在屏幕顶部看到通知显示.我什至锁定"了屏幕,它没有显示.我收到了通知声音,我的日志显示我收到了.

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.

显示收到通知的屏幕

我的 FirebaseMessageService:

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

推荐答案

只有当应用程序处于后台或关闭时,系统托盘中的通知才会显示.如果您的应用程序正在运行,您的 OnMessageRecieved 方法将被命中,但是 Android 不会在系统尝试中显示通知.这就是推送通知的生命周期在 Android 中的工作原理.当应用程序在前台时,您可以在系统托盘中显示通知的唯一方法是像在 SendLocalNotification 方法中那样强制本地通知.

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.

这篇关于Xamarin Android 通知未显示在前台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆