Random geekery since 2005.

Husband, father, programmer, speaker, writer, blogger, podcaster, collector, traveler, golfer.

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

Tags

18 responses to “31 Days of Windows Phone | Day #19: Push Notifications”

  1. Rob Streno Avatar

    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. Ian Bennett Avatar
    Ian Bennett

    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. John Marshall Avatar
    John Marshall

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

  4. sonic payday loans Avatar

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

  5. apply for personal loan Avatar

    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. loan cash Avatar

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

  7. on line cash advance Avatar

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

  8. personal loans poor credit Avatar

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

  9. small personal loans Avatar

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

  10. check loan Avatar

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

  11. fast loan approval Avatar

    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. loan til payday Avatar

    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. pay day cash loans Avatar

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

  14. quick pay loans Avatar

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

  15. best bad credit loan Avatar

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

  16. emergency loan Avatar

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

  17. merchant cash advance Avatar

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

  18. Kenney Avatar
    Kenney

    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 )

Facebook photo

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

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: