首页 > 解决方案 > FCM - 仅在应用程序处于后台时“显示”推送通知

问题描述

目前,我在我的 Xamarin 应用程序中发送和接收推送通知。当我发送推送通知时,当应用程序位于前台和后台时,会显示潜行高峰对话。当应用程序在后台时,我试图仅视觉显示推送通知。当用户在前台时,通知只是潜入 HUD 而不会显示。

这是我的代码:

Xamarin Android

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FCMMessagingService : FirebaseMessagingService
{
    const string TAG = "MyFirebaseMsgService";
    public override void OnMessageReceived(RemoteMessage message)
    {
        try
        {
            var _message = message.GetNotification().Body;
            var _title = message.GetNotification().Title;
            MainActivity.SendNotification(_title, _message);
        }
        catch (Exception e)
        {
            //Was NotificationType null? this should never be null anyways
        }
    }
}

API - Android 负载

    return new JObject(
           new JObject(
                   new JProperty("notification",
                       new JObject(
                           new JProperty("body", message),
                           new JProperty("title", title),
                           new JProperty("icon","toasticon"), 
                           new JProperty("user", fromId != null ? fromId.ToString() : "")
                        )
                    ),
                   new JProperty("data",
                        new JObject(
                            new JProperty("notificationtype", notificationType)
                            )
                   )
                )
       ).ToString();

标签: firebasexamarinxamarin.androidfirebase-cloud-messaging

解决方案


如果您已遵循xamarin android 的 firebase 设置

您可能在那里读到过必须手动显示前台通知,

怎么做?

这是如何

在设置中,您将拥有一个继承自的类FirebaseMessagingService

在那个类中,会有一段类似这样的代码():

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

var notificationBuilder = new  NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                          .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                          .SetContentTitle("FCM Message")
                          .SetContentText(messageBody)
                          .SetAutoCancel(true)
                          .SetContentIntent(pendingIntent);

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

这段代码将通知发送到 Android 托盘,当在前台时,因此如果您对此发表评论,您将获得所需的输出。

祝你好运!

在查询恢复的情况下。


推荐阅读