31 Days of Windows Phone | Day #19: Push Notifications

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.

  1. 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.
  2. 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):

http://sn1.notify.live.net/throttledthirdparty/01.00/AAHsLicyiJgtTaiDbJoSgmFiAgAAAAADAwAAAAQUZm52OjlzOEQ2NDJDRkl5MEVFMEQ

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!

download

18 thoughts on “31 Days of Windows Phone | Day #19: Push Notifications

  1. Jeff:

    Is the phone app responsible for contacting the back-end server to let them know what the notification URL is for their phone, or is there a way for the back-end server to query the notification service to retrieve a list of notification URLs?

    If it is the former, is it a best practice to have the app "re-register" it's notification URL whenever the app is activated (in case the back-end server has lost it)?

    Rob

  2. Good question, I also would like to know the answer.

    Also I assume it's up to the client to inform the webservice as to what information it is interested in? ie. I only want weather updates for Dublin,London & New York etc?

  3. A small admin point.
    The download for this session is labelled as day 20 rather than day 19.

  4. Go often to the house of thy friend, for weeds choke the unused path.

  5. All our progress is an unfolding, like a vegetable bud. You have first an instinct, then an opinion, then a knowledge as the plant has root, bud, and fruit. Trust the instinct to the end, though you can render no reason.

  6. For most men the love of justice is only the fear of suffering injustice.

  7. My advice to you is get married if you find a good wife youll be happy if not, youll become a philosopher.

  8. Animals are such agreeable friends – they ask no questions, they pass no criticisms.

  9. Show me the man who keeps his house in hand, He's fit for public authority.

  10. Things that are done, it is needless to speak about…things that are past, it is needless to blame.

  11. The man who in view of gain thinks of righteousness who in the view of danger is prepared to give up his life and who does not forget an old agreement however far back it extends – such a man may be reckoned a complete man.

  12. Once you agree upon the price you and your family must pay for success, it enables you to ignore the minor hurts, the opponent's pressure, and the temporary failures.

  13. You cannot truly listen to anyone and do anything else at the same time.

  14. Fiction is obliged to stick to possibilities. Truth isn't.

  15. Tomorrow night I appear for the first time before a Boston audience of 4000 critics.

  16. Perpetual devotion to what a man calls his business, is only to be sustained by perpetual neglect of many other things.

  17. People grow through experience if they meet life honestly and courageously. This is how character is built.

  18. A great example of how to use notifications in Windows Phone 7, but as sending multiple or mass amount of notifications can be tricky or requires code to be created to handle replies and retries, i wanted to point you in the direction of a new service, which will handle Sending push notifications with autmatic retries etc. Free account which fits the needs of the single developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s