Windows Store App Notifications, the Notification Hub and Background tasks
This article aims to talk about Windows Store Notifications and the Windows Azure Notifications Hub and it will attempt to collate the various articles in a single place to help you build notifications into your app.
In order for you to get an understanding of Windows notifications look at the following article
Introduction to Push Notifications - http://msdn.microsoft.com/en-us/library/windows/apps/hh913756.aspx. this provides a good overview of how push notifications work. To summarise the important bits.
1. Your store app needs to register with the Windows Notification Service to retrieve a unique URI for your instance of the app. Ideally you do this each time the app starts.
2. If the URI has changed then you need to notify your service that there is a new URI. Note: This URI expires every 30 days so your app needs to notify your service that this has been changed.
3. Your service sends notifications to this unique URI
You may have noticed above that I mentioned “Your service”. This is a critical piece of the notification mechanism and there are a number of ways to build this service. If you are not comfortable building backend services or you want something up and running quickly then mobile services might be the way to go for you. Here’s a tutorial that gets you started with mobile services http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started/
If, like me, you already have a source of data and a service then you will probably want to wire in notifications into your existing service. depending upon how many devices you have using your app may dictate the method that you get the notifications onto the users device. there are a number of options:
- Local updates
- Push Notifications
- Periodic Notifications
Local updates require the creation of a background task that Windows runs periodically that calls into your data service, retrieves the data to put on the tiles and sends out tile notifications using the Windows Store app SDK
Updating live tiles from a background task - http://msdn.microsoft.com/en-us/library/windows/apps/jj991805.aspx. Provides a tutorial on building a background task for your Windows Store App. this tutorial is for timer tasks but it can easily be used for push notification tasks. The bits that are likely to change are the details of the run method, the task registration and the package manifest.
Two more important links that you will require when you are dealing with notifications:
Tile template catalogue http://msdn.microsoft.com/en-us/library/windows/apps/hh761491.aspx
Toast template catalogue http://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx
These two catalogues are important as they provide you with details of the xml you need for each type of notifications
Push notifications are sent through the Windows Notification Service to your device.
You can send notifications to your device from your service by creating a notification and sending it to each of the devices registered to your service via the Windows Notification Service.
If you have a large number of devices running your app then you will probably want to use the Windows Azure Notification Hub. This is the simplest way to manage notifications to your application as the notification hub handles scaling, managing of the device registration and also iterating around each device to send the notifications out. The Notification hub will also allow you to send notifications to Windows Phone, Apple and Android devices. To get started with the notification hubs follow this tutorial:http://www.windowsazure.com/en-us/manage/services/notification-hubs/getting-started-windows-dotnet/
The nice feature of the notification hub is that is makes the code needed to send notifications simple.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("
var toast = @"
await hub.SendWindowsNativeNotificationAsync(toast);
Compare this to the code to send the notification without the hub:
byte[] contentInBytes = Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = HttpWebRequest.Create(uri) asHttpWebRequest;
request.Method =
"POST";
request.Headers.Add(
"X-WNS-Type", notificationType);
request.ContentType = contentType;
request.Headers.Add(
"Authorization", String.Format("Bearer {0}", accessToken.AccessToken));
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(contentInBytes, 0, contentInBytes.Length);
In addition you will need to retrieve the list of devices that are registered for push notifications and iterate around the list to send this to each device. You will also require a service that receives the registrations and stores them in a data store. You need to manage the scalability of these services. On the down side the notification hub is charged per message which means the more often you send notifications the greater the costs where as hosting a service is load based and the notifications will be sent out slower as the number of devices increases but this would generally be a lower cost. If you also take into account that you will need to send out notifications for each tile size and that will increase the activity count on the notification hub for each tile size (currently 3).
[Update: You can send out a single notification for all tile sizes rather than 3 separate notifications by adding a binding for each tile size in your xml see http://msdn.microsoft.com/en-us/library/windows/apps/hh465439.aspx for more details]
It is possible to send custom notifications to your app which can be received directly in the app or by using a background task. These are called Raw notifications. In order to receive raw notifications in a background task your app needs to be configured to display on the start screen. However Raw Notifications can be received in your app whilst it is running when it is not configured to display on the start screen. A Raw Notification is a block of data up to 5KB in size and can be anything you want.
The following code will send a raw notifications using the notifications hub:
string rawNotification = prepareRAWPayload();
Notification notification = new Microsoft.ServiceBus.Notifications.WindowsNotification(rawNotification);
notification.Headers.Add(
"X-WNS-Cache-Policy", "cache");
notification.Headers.Add(
"X-WNS-Type", "wns/raw");
notification.ContentType =
"application/octet-stream";
var outcome = await hub.SendNotificationAsync(notification);
In order to receive Raw Notifications in your app you need to add an event to the channel you retrieve from the Windows Notification Service:
var channel = awaitPushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channel.PushNotificationReceived += channel_PushNotificationReceived;
And then handle the notification received:
privatevoid channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
switch (args.NotificationType)
{
casePushNotificationType.Raw:
ReceiveNotification(args.RawNotification.Content);
break;
}
}
Note: the content of the notification is the block of data that you sent out.
Sample background task for Raw Notifications is here: http://msdn.microsoft.com/en-us/library/windows/apps/jj709906.aspx
Guidelines for Raw Notifications can be found here: http://msdn.microsoft.com/en-us/library/windows/apps/hh761463.aspx
Periodic notifications also require a service but the application periodically calls into a service to retrieve the tile notifications without needing to process the source data and then create the notifications locally. details about how to use periodic notifications can be found here: http://msdn.microsoft.com/en-US/library/windows/apps/jj150587
In summary Windows Store application notifications can be send to the app in a variety of ways and the mechanism you choose will depend upon how quick and how many notifications are required. Push notifications allow notifications to be sent whenever they are ready to send. Periodic and Local updates are pull notifications and require a service to be available to pull the data from. All of these will require some sort of service and all have an associated costs. The notifications hub is a useful tool to assist with notifications and it can be useful to manage the device connections as well as sending out notifications to multiple device type. It does however come at a cost and you need to work out whether it is a cost effective mechanism for your solution.