代码之家  ›  专栏  ›  技术社区  ›  Christine

当应用程序未运行时,如何定义数据负载firebase通知的标题?

  •  0
  • Christine  · 技术社区  · 6 年前

    我正在将一个基于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"/>
    

    但这两种方法都没有奏效。

    enter image description here

        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());
        }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Christine    6 年前

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

    .SetContentTitle(AppInfo.DisplayName)
    

    appinfo.displayname在mainActivity的oncreate方法中设置。我将变量替换为:

    .SetContentTitle(ApplicationInfo.LoadLabel(PackageManager))
    

    在应用程序未运行时接收的通知中显示应用程序名称作为标题。感谢山猫指点我正确的方向!