【问题标题】:Xamarin.Android FCM Notification does not display in HUD While app closed/backgroundingXamarin.Android FCM 通知在应用程序关闭/后台时不显示在 HUD 中
【发布时间】:2018-08-20 03:51:47
【问题描述】:

我在 Oreo 设备上遇到了一个问题,当通知发送给客户端时,通知根本不会显示在面板中。我可以确保在后台接收到它们,因为我创建了自定义振动效果 OnMessageReceived 并且这可以工作,但 Android HUD 中仍然没有显示任何内容。

另外,我注意到另一篇文章说 Visual Studio 在强制关闭时会终止通知服务。这是真的,因为它也杀死了我的振动效果,但是在加载了应用程序端后,我可以从设备启动并触发我的自定义效果。

我相信我正在做的是 1,将我的标签注册到 Azure-FCM 服务。 第二,我是说注册我的 API 端点以及允许的模板。 我认为我正在注册的有效负载模板有问题, 以及我发送的有效载荷

见下文..

Web API that generates Android payload
private string GetAndroidAlertJson(int? fromId, int notificationType, string message)
    {
        return new JObject(


           new JProperty("data",
               new JObject(
                   new JProperty("notification",

                       new JObject(
                           new JProperty("badge", 1),
                           new JProperty("body", message),
                           new JProperty("title", "wazzup?!"),
                           new JProperty("priority", "high")
                        )
                    ),
                   new JProperty("type_id", notificationType),
                   new JProperty("user", fromId != null ? fromId.ToString() : ""),
                   new JProperty("message", message)
                )
           )
       ).ToString();
    }

Xamarin.Android

//NotificationBuilder
return new NotificationCompat.Builder(ApplicationContext, PRIMARY_CHANNEL)
                 .SetContentTitle(title)
                 .SetContentText(body)
                 .SetSmallIcon(SmallIcon)
                 .SetPriority(2)
                 .SetVibrate(new long[0])
                 .SetAutoCancel(true);
//In MainActivity
public NotificationHelper(Context context) : base(context)
    {
        var chan1 = new NotificationChannel(PRIMARY_CHANNEL,
                PRIMARY_CHANNEL, NotificationImportance.Max);
        chan1.LightColor = 2;
        chan1.LockscreenVisibility = NotificationVisibility.Public;
        Manager.CreateNotificationChannel(chan1);
    }
public NotificationCompat.Builder GetNotification1(String title, String body)
    {
        return new NotificationCompat.Builder(ApplicationContext, PRIMARY_CHANNEL)
                 .SetContentTitle(title)
                 .SetContentText(body)
                 .SetSmallIcon(SmallIcon)
                 .SetPriority(2)
                 .SetVibrate(new long[0])
                 .SetAutoCancel(true);
    }
 FCMService
 [Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FCMMessagingService : FirebaseMessagingService
{//Foreground Only
    const string TAG = "MyFirebaseMsgService";
    public override void OnMessageReceived(RemoteMessage message)
    {
        if (Debugger.IsAttached)
            Debugger.Break();
        CustomNotificationEffect();
        try
        {
            if (message.Data.Count > 0)
            {
                var type_id = Convert.ToInt32(RetreiveNotification("type_id"));
                var body = RetreiveNotification("message");
                MainActivity.SendNotification(type_id, body);
            }
        }
        catch (Exception e)
        {
            //Was NotificationType null? this should never be null anyways
        }
        string RetreiveNotification(string key)
        {
            string value = String.Empty;
            message.Data.TryGetValue(key, out value);
            return value;
        }
    }
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FCMInstanceIDService : FirebaseInstanceIdService
{
    const string TAG = "MyFirebaseIIDService";
    public static string ProfilePushTag;
    public async override void OnTokenRefresh()
    {
        var refreshedToken = FirebaseInstanceId.Instance.Token;
        Console.WriteLine("Token Received!: " + refreshedToken);
        await SendRegistrationToServer(refreshedToken);
    }
    public async Task SendRegistrationToServer(string token)
    {
        //We will have to send our token to the server here
        //

        string templateBodyFCM =
            "{" +
            "\"notification\" : {" +
            "\"body\" : \"$(messageParam)\"," +
            "\"title\" : \"Xamarin U\"," +
            "\"icon\" : \"myicon\" }}";
        var templates = new JObject();
        //templateBodyFCM = "Pyx";
        templates["genericMessage"] = new JObject
        {
            { "body", templateBodyFCM}
        };


        try
        {

            var tags = new List<string>();
            if (!String.IsNullOrWhiteSpace(ProfilePushTag))
            {
                // Register with Notification Hubs
                var hub = new NotificationHub("HUB-NAME",
                                      "AZURE-ENDPOINT"
                                      , this);
                tags.Add(ProfilePushTag);
                var regID = hub.Register(token, tags.ToArray()).RegistrationId;



                var hub2 = new MobileServiceClient("https://MyAPI");
                await hub2.GetPush().RegisterAsync(token, templates);
            }
        }
        catch (Exception e)
        {

        }
    }

【问题讨论】:

  • 在 FCM 中客户端注册接收到的可接受的负载模板。也许一个线索是我用来注册服务器的模板,它是 string templateBodyFCM = "{" + "\"notification\" : {" + "\"body\" : \"$(messageParam)\", " + "\"title\" : \"Xamarin U\"," + "\"icon\" : \"myicon\" }}";
  • 我刚刚读到“通知”键在后台不起作用stackoverflow.com/questions/37711082/…
  • 你为奥利奥创建了通知渠道吗?如果没有,请查看medium.com/globallogic-latinoamerica-mobile/…
  • 是的,我确实创建了一个 NotificationChannel 并且还使用了 NotificationManager.CreateFromNotificationChannel 方法...我认为答案可能在这里stackoverflow.com/questions/50643502/…
  • 是的,那你为什么不改变你的有效载荷呢?

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


【解决方案1】:

Android O 中,必须将频道与通知生成器一起使用 以下是您应该如何使用它的示例代码:

public NotificationCompat.Builder GetNotification1(String title, String body) {
 var mynotif = new Notification.Builder(ApplicationContext)
  .SetContentTitle(title)
  .SetContentText(body)
  .SetSmallIcon(SmallIcon)
  .SetPriority(2)
  .SetVibrate(new long[0])
  .SetAutoCancel(true);
 if (Build.VERSION.SdkInt >= BuildVersionCodes.O) {
  mynotif.SetChannelId(PRIMARY_CHANNEL);
 }

}

【讨论】:

    【解决方案2】:

    如果您查看我的 Web API,您会发现所有内容都包含在“数据”类型中。根据这篇文章How to handle notification when app in background in Firebase,HUD 中不会显示“数据”类型,但会显示“通知”类型。删除此属性解决了问题,现在显示在 HUD 中。

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 2022-12-22
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      相关资源
      最近更新 更多