Send push notification to all registered devices with Azure Notification Hub in .NET
我正在使用Azure Notification Hub,并且我想向.NET后端中的所有已注册设备发送推送通知消息。但是我不确定这种方式是否可以发送到所有设备,因为我没有办法检查收到的推送消息的设备数量。
那么,如何将推送消息发送到所有设备,或者可以确保这种方式正确?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static async Task<bool> SendBroadcast(string msg) { try { var notificationHubClient = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["ServiceBusPushNotificationConnectionString"], ConfigurationManager.AppSettings["ServiceBusPushNotificationName"]); Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("message", msg); param.Add("alert", msg); var template = new TemplateNotification(param); var result = await notificationHubClient.SendNotificationAsync(template); Console.WriteLine(JsonConvert.SerializeObject(result)); return true; } catch (Exception exception) { Console.WriteLine(exception.Message); return false; } } |
如果您未指定任何标签表达式,则表示它已广播。所有设备都会收到通知。您可以使用"每条消息遥测"来跟踪接收到多少设备。请参见以下链接。
https://msdn.microsoft.com/zh-CN/library/azure/mt608135.aspx
https://azure.microsoft.com/zh-cn/blog/push-notification-hub-telemetry-expiry-update/
您需要使用"路由和标签表达式"中所述的标签:
The only way to target specific registrations is to associate them
with a tag, then target that tag. As discussed in Registration
Management, in order to receive push notifications an app has to
register a device handle on a notification hub. Once a registration is
created on a notification hub, the application backend can send push
notifications to it. The application backend can choose the
registrations to target with a specific notification in the following
ways:Broadcast: all registrations in the notification hub receive the
notification.Tag: all registrations that contain the specified tag receive the
notification.Tag expression: all registrations whose set of tags match the
specified expression receive the notification.
请注意,您需要考虑广播消息的局限性。
有关如何使用广播通知的详细信息,请查看最新新闻应用示例。