如何在通知中心中设置GCM / FCM有效负载的生存时间

时间:2017-01-07 09:20:29

标签: android google-cloud-messaging firebase-cloud-messaging azure-mobile-services azure-notificationhub

我正在使用带有FCM的通知中心向我的Android应用程序发送通知。我想在每个通知中另外设置消息优先级和生存属性的时间,但是通知中心期望在HubClinet上的SendGcmNativeNotificationAsync方法中使用jsonpayload和标签。我不确定如何在有效负载中添加这些附加属性。

1 个答案:

答案 0 :(得分:3)

我们可以在自定义模型中以正确的格式添加这些属性,然后将其转换为json payload。

public class GcmNotification
{
    [JsonProperty("time_to_live")]
    public int TimeToLiveInSeconds { get; set; }
    public string Priority { get; set; } 
    public NotificationMessage Data { get; set; }
}


 public class NotificationMessage
 {
   public NotificationDto Message { get; set; }
 }

 public class NotificationDto
 {
        public string Key { get; set; }
        public string Value { get; set; }
 }

调用SendNotification方法并传递您的模型。现在您可以使用json转换器转换数据,但请记住在JsonConverter中使用小写设置,否则可能会在设备上进行预测。我在LowercaseJsonSerializer类中实现了这个。

 private void SendNotification(GcmNotification gcmNotification,string tag)
  {
     var payload = LowercaseJsonSerializer.SerializeObject(gcmNotification);
     var notificationOutcome = _hubClient.SendGcmNativeNotificationAsync(payload, tag).Result;
 }

public class LowercaseJsonSerializer
    {
        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new LowercaseContractResolver()
        };

        public static string SerializeObject(object o)
        {
            return JsonConvert.SerializeObject(o,Settings);
        }

        public class LowercaseContractResolver : DefaultContractResolver
        {
            protected override string ResolvePropertyName(string propertyName)
            {
                return propertyName.ToLower();
            }
        }
    }
相关问题