【问题标题】:How to set time to live to GCM/ FCM payload in notification hub如何在通知中心设置 GCM/FCM 有效负载的生存时间
【发布时间】:2017-05-22 01:12:51
【问题描述】:
我正在使用带有 FCM 的通知中心向我的 Android 应用程序发送通知。我想为每个通知设置消息优先级和时间属性,但通知中心在 HubClinet 上的 SendGcmNativeNotificationAsync 方法中需要 jsonpayload 和标签。我不确定如何在有效负载中添加这些附加属性。
【问题讨论】:
标签:
android
google-cloud-messaging
firebase-cloud-messaging
azure-mobile-services
azure-notificationhub
【解决方案1】:
我们可以将这些属性以正确的格式添加到我们的自定义模型中,然后将其转换为 json 负载。
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();
}
}
}