【问题标题】:How do I define a title for a data-payload firebase notification when the app is not running?当应用程序未运行时,如何定义数据有效负载 Firebase 通知的标题?
【发布时间】:2018-07-11 18:21:33
【问题描述】:

我正在将基于 GCM 的消息传递应用程序转换为 firebase。使用数据有效负载格式将消息发送到应用程序。如果我的应用程序正在前台或后台运行,则 OnMessageRecieved 中的代码将运行并设置通知标题。但是,如果收到通知时应用程序未运行,则不会显示标题。我尝试为数据负载添加标题:

{
    "data": {
        "title": "My Title",
        "message": "Text of the message",
    }
}

也尝试在AndroidManifest.xml中按照定义图标的格式定义:

<meta-data android:name="com.google.firebase.messaging.default_notification_title" android:value="My Title"/>

但是这些方法都没有奏效。

    public override void OnMessageReceived(RemoteMessage message)
    {
        try
        {
            SendNotification(message.GetNotification()?.Body, message.Data);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    void SendNotification(string messageBody, IDictionary<string, string> data)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        foreach (string key in data.Keys)
        {
            if (key == "message")
                messageBody = data[key];
            else
                intent.PutExtra(key, data[key]);
        }
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new Notification.Builder(this)
            .SetSmallIcon(Resource.Drawable.smallicon)
            .SetContentTitle(AppInfo.DisplayName)
            .SetContentText(messageBody)
            .SetAutoCancel(true)
            .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
            .SetContentIntent(pendingIntent);

        var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(0, notificationBuilder.Build());
    }

【问题讨论】:

  • 为什么不在 onMessageReceived 中自己创建通知?
  • 发布您的onMessageReceived() 代码。
  • tyczj - OnMessageRecieved 在应用未运行时不会运行。
  • 您是说当您的应用未运行时,您帖子中显示的无标题通知不是由您的onMessageReceived() 代码生成的,而是由 Firebase 消息处理代码生成的?我认为像您展示的那样data-only message 是不可能的。
  • @BobSnyder - 这是我的假设,但由于我无法调试,我在 SendNotification 中的消息中添加了“-OnMessageRecieved”,并且在应用程序未运行时收到的通知中确实显示了,所以这个假设是不正确的。

标签: android firebase notifications firebase-notifications


【解决方案1】:

原来 OnMessageRecieved 正在运行,问题在于标题本身的设置:

.SetContentTitle(AppInfo.DisplayName)

AppInfo.DisplayName 在 MainActivity 的 OnCreate 方法中设置。我将变量替换为:

.SetContentTitle(ApplicationInfo.LoadLabel(PackageManager))

这会将应用名称显示为应用未运行时收到的通知中的标题。感谢 BobSnyder 为我指明了正确的方向!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2017-03-11
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多