FCM-仅在应用程序处于后台时“显示”推送通知

时间:2018-09-21 05:19:47

标签: firebase xamarin xamarin.android firebase-cloud-messaging

当前,我在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();

1 个答案:

答案 0 :(得分:1)

如果您遵循了firebase setup for xamarin android

您可能已经读过,必须手动显示前台通知,

该怎么做?

这是

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

的类

在该类中,将有一段类似于this()的代码:

 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任务栏,当它处于前台时,因此如果您对此进行评论,您将获得所需的输出。

祝你好运!

如果恢复查询。

相关问题