This post is Day #19 in a series called the 31 Days of Windows Phone.
Yesterday, I wrote about the WebBrowser control, and how to leverage it in your applications. Today, we’re going to talk about, quite possibly, the most important topic in this series: Push Notifications.
If you’re not familiar with the concept of Push Notifications, it’s pretty simple: instead of forcing your application to check the server for new data every few minutes, your server has the ability to tell your phone when there’s new data.
Why Use Push Notifications?
For one, you’ll save your user’s battery. Calling back to a server to check for data takes power, and on a phone, power is an absolute scarcity. You’ll never have enough, and no matter how long your battery lasts, avoiding push notifications will only make that time shorter.
Secondly, you can leverage push notifications to let your user know that something interesting is happening with your application, even if it’s not running. You can alert the user that they should open your application to interact with whatever it is you needed to tell them.
The Push Notification Process
So that you understand all of the code I’m about to throw at you, I thought it might be a good idea to explain exactly what is happening in this process.
- The first time a user runs your application on their phone, the app will call out to Microsoft’s Push Notification service, requesting a custom URI for communications purposes.
- When an event happens on your web service, you should pass messages to that URI (with a specific payload), and the Push Notification services will deliver that data to your user’s phone, in the form of a Live Tile update, a Toast notification, or as actual data to your application.
This article is going to focus on the “how” of each of the above bullet points. If you want to see an example that you can build step-by-step, check out the Windows Phone Developer Training Kit. It’s got an outstanding Push Notification tutorial that you can use.
Retrieving a Custom URI from the Push Notification Service
Thankfully, they’ve made this part incredibly simple. We need to use the Microsoft.Phone.Notification assembly, but otherwise, we can get a custom URI from the Push Notification service (PNS) in about 10 lines of code. First, we’ll create a new HttpNotificationChannel. This will automatically communicate with the PNS (on a seperate thread), and we’ll create an event to capture what the service returns.
HttpNotificationChannel channel; void GetPushChannel() { channel = new HttpNotificationChannel("BLANKENSOFT_" + DateTime.Now.Ticks.ToString()); channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated); channel.Open(); } void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Dispatcher.BeginInvoke(delegate { URIBlock.Text = channel.ChannelUri.ToString(); }); }
The custom URI I received from this example was (it’s small so it fits):
Once you have the URI, you’ll want to save that to your web service. It’s your web service that will be initiating the messages to the phone, and we can do that one of three ways: Tile notification, Toast notification, or a Raw notification. We’ll cover each of these in the next section.
Different Messages For Different Needs
Earlier I mentioned that there are three different types of messages you can send to a phone. Here’s a quick outline of what those are:
Raw Notification – Raw notifications are used when your application is actually running on the device. This allows you to update your interface “live” as the user is using it.
Toast Notification – This message will be received regardless of whether your application is running or not, but popping toast messages while your app is running might be a little annoying. I’ll demonstrate this example below. Toast WILL NOT also update your application’s data. You still need to pass a Raw Notification to make this happen.
Tile Notification – If your application is pinned to the user’s Start screen, you can update the Tile for your application. You can change the background image, as well as an integer from 0-99.
Sending a Toast Notification
Once we’ve got our Push URI, it’s just a matter of composing an HTTP message, and sending it to that URI. Here’s an example in code:
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channel.ChannelUri.ToString()); sendNotificationRequest.Method = "POST"; //Indicate that you'll send toast notifications! sendNotificationRequest.ContentType = "text/xml"; sendNotificationRequest.Headers = new WebHeaderCollection(); sendNotificationRequest.Headers.Add("X-NotificationClass", "2"); if (string.IsNullOrEmpty(txtMessage.Text)) return; //Create xml envelope string data = "X-WindowsPhone-Target: toastrnrn" + "<?xml version='1.0' encoding='utf-8'?>" + "<wp:Notification xmlns:wp='WPNotification'>" + "<wp:Toast>" + "<wp:Text1>{0}</wp:Text1>" + "</wp:Toast>" + "</wp:Notification>"; //Wrap custom data into envelope string message = string.Format(data, txtMessage.Text); byte[] notificationMessage = Encoding.Default.GetBytes(message); // Set Content Length sendNotificationRequest.ContentLength = notificationMessage.Length; //Push data to stream using (Stream requestStream = sendNotificationRequest.GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } //Get reponse for message sending HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse(); string notificationStatus = response.Headers["X-NotificationStatus"]; string notificationChannelStatus = response.Headers["X-SubscriptionStatus"]; string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
As you can see, the code for this portion can get long and convoluted quickly. My recommendation is to spend some time going through the Windows Phone Developer Training Kit, and specifically walking through the Push Notification example.
It’s an outstanding example of how push notifications work (from front to back), and shows you just how powerful these updates can be to keep your application in front of your user’s eyes.
Download The Code
For today’s example, downloading the above code won’t do you much good without all of the context that it requires. Today’s download is actually the final example from the Push Notification demo in the Windows Phone Developer Training Kit. Enjoy!
Leave a Reply