Mobile Zone is brought to you in partnership with:

I love technology. Plain and simple. You can generally find me writing software, figuring out how to get rid of cable, playing on my Xbox, or traveling around this country speaking about software development. If you're doing something cool with technology, let me know. I'd love to hear your story about something amazing. You can find my blog at jeffblankenburg.com Jeff is a DZone MVB and is not an employee of DZone and has posted 71 posts at DZone. You can read more from them at their website. View Full User Profile

31 Days of Windows 8 | Day #10: Toast Notifications

11.13.2012
| 4692 views |
  • submit to reddit

This article is Day #10 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Yesterday, we spent some time looking at Live Tiles, and how to let your users know about important information from your app.  Today, we’re looking at a different type of user notification: Toast Notifications.

If you haven’t worked with Toast Notifications in the past, the word might seem a little silly to you.  The word “toast” in this case, comes from the image of a piece of toast emerging from a toaster.  Our notifications appear in a similar way, popping up in front of our user to let them know when something interesting has happened.

The primary difference between Toast notifications and Live Tile notifications is that Toast messages will appear on the user’s screen regardless of which app they are currently running.  Live Tiles have to be viewed on the user’s Start Screen.

Toast messages scream “YOU NEED TO KNOW THIS INFORMATION RIGHT NOW!” where Live Tiles are significantly more passive.  Be sure you consider this when you’re sending toast messages.  If you’re spamming them with unimportant nonsense, they’re going to turn off your ability to send notifications, or worse, uninstall your app.  Make sure you take a little time to read Microsoft’s guidance on toast notifications before you get too deep into this.

For reference, here’s a few examples of Toast notifications.

ToastText01 example

ToastImageAndText01 example

Just like Live Tiles, there’s an entire catalog of Toast Notification types you can use, but we’ll get to those in a moment.

Enabling Toast Notifications in Your App

Our first step to greatness with Toast Notifications is actually enabling them in our application manifest.  Open your package.appxmanifest file to the Application UI tab, and select “Yes” from the “Toast capable” dropdown list.

10-XAML-EnableToastNotifications

It will be very tempting, as you go through this article, to create a Badge logo file, and upload it to your application, but for this tutorial, don’t.  Here’s why:

If you upload a Badge Logo, you must enable Lock Screen Notifications.  However, if Lock Screen Notifications are enabled, you must have a Background Task.  We’re not covering Background tasks for two more days, and Lock Screen updates are tomorrow. Just be patient. :)

Today, we’re focused on notifying the user via a Toast message.  Let’s get to that.

Launching a Toast Notification from Your App

Yesterday, Day #9’s article focused on Live Tiles, and if you read that, launching Toast Notifications is going to seem incredibly familiar.  Here’s the code you need to make it happen:

ToastTemplateType toastType = ToastTemplateType.ToastImageAndText02;
XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastText = toastXML.GetElementsByTagName("text");
XmlNodeList toastImages = toastXML.GetElementsByTagName("image");
toastText[0].InnerText = "Funny cat";
toastText[1].InnerText = "This cat looks like it's trying to eat your face.";
((XmlElement)toastImages[0]).SetAttribute("src", "ms-appx:///Assets/10-XAML-CatImageSmall.png");
((XmlElement)toastImages[0]).SetAttribute("alt", "Scary Cat Face");
 
ToastNotification toast = new ToastNotification(toastXML);
ToastNotificationManager.CreateToastNotifier().Show(toast);

As we did with Live Tiles, we do with Toast.  The first line selects our Toast Template.  We then grab the XML for that template and store it in toastXML.  Here’s what the XML for this template looks like:

<toast>
    <visual>
        <binding template="ToastImageAndText02">
            <image id="1" src="image1" alt="image1"/>
            <text id="1">headlineText</text>
            <text id="2">bodyText</text>
        </binding>  
    </visual>
</toast>

As you can see, we have two text properties, and one image property.  The next steps in our code sample above was to assign values to those properties.  For the image, you’ll notice I added an extra line this time, referencing the “alt” attribute.  If you’ve done any web development before, you probably already know what that is, but it’s an important piece of the accessibility story on Windows 8.  It provides a text representation of the image, for those users that are unable to see their screen.

Finally, we create a new ToastNotification object, and Show() it on the screen.  That’s the simple story to creating toast notifications in Windows 8.  And here’s what that exact tile looks like on my machine:

10-XAML-CatToast

But wait, there’s more!  If you created a project, and launched the toast message, you may have noticed that there is an audio clip that goes with it.  This is the default Toast Notification sound, but you have options.  There’s also some other cool things you can do with toast messages.

Setting the Audio for a Toast Notification (and more!)

Everything about creating a Toast Notification stays the same, but we can add some additional nodes to our XML to select a different audio sound, set the duration of the message, and even dictate a page to launch when the notification is clicked (with query parameters as well!)

First, regarding audio, I have some bad news.  You can’t use your own custom audio file.  I know you were hoping to delight your user with the sound of a popping toaster, but it’s just not possible.  Instead, you can select from a list of 9 audio files, 4 of which are looping sounds that can be used like ringtones or alarms.  You can see the entire list of the audio files and descriptions available to Toast Notifications here.

To set the audio, we first need to crack open the XML we’ve been creating.  By default, none of the Toast Templates have an audio node defined, so we need to create one.  First, we need to dive into the <toast> node of our template, and then we can set our options.  In the code sample below, I’ve included the exact same Toast notification from earlier in this article, but with some comments explaining the new lines for our optional options.

ToastTemplateType toastType = ToastTemplateType.ToastImageAndText02;
XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastText = toastXML.GetElementsByTagName("text");
XmlNodeList toastImages = toastXML.GetElementsByTagName("image");
toastText[0].InnerText = "Funny cat";
toastText[1].InnerText = "This cat looks like it's trying to eat your face.";
((XmlElement)toastImages[0]).SetAttribute("src", "ms-appx:///Assets/10-XAML-CatImageSmall.png");
((XmlElement)toastImages[0]).SetAttribute("alt", "Scary Cat Face");
 
//This is the options code, which is all optional based on your needs.
IXmlNode toastNode = toastXML.SelectSingleNode("/toast");
            
((XmlElement)toastNode).SetAttribute("duration", "long");
 
XmlElement audioNode = toastXML.CreateElement("audio");
audioNode.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Alarm");
 
//Must be used when looping audio has been selected.
audioNode.SetAttribute("loop", "true");
toastNode.AppendChild(audioNode);
 
//You can append any text data you would like to the optional
//launch property, but clicking a Toast message should drive
//the user to something contextually relevant.
((XmlElement)toastNode).SetAttribute("launch", "<cat state='angry'><facebite state='true' /></cat>");
 
ToastNotification toast = new ToastNotification(toastXML);
ToastNotificationManager.CreateToastNotifier().Show(toast);

It’s important to remember that all of the options are optional, as you could see by their absence in our first example.  Here’s a couple of things to remember about these options:

  • Long duration Toast messages are meant for things like VOIP calls and alarm clocks, not for email notifications.  Use this sparingly.
  • All of the looping audio options that are available will only work if you have set the duration to Long.
  • The looping audio options will only work if you also set the “loop” attribute to true.

Failure to follow those rules will result in the Notification.Default audio to be played instead.

In addition, you might want to have SILENCE for your toast message instead of any of the audio options.  You can do that.  In that case, you still specify an audioNode, but you set a new attribute, silent, to true, like this:

audioNode.SetAttribute("silent", "true");

This will result in a silent, but otherwise normal toast notification for your user.  Finally, there’s the “launch” attribute.  Within this, we can pass any text string that we’d like, and it will be passed back to us as a page parameter when the toast message is pressed by the user.  This data should allow you to determine which page to direct them to, with which data populating it.  Don’t put anything in the “launch” parameter that doesn’t need to make the trip.

Summary

That’s about it for Toast Notifications in Windows 8.  Very similar to Live Tiles, toast messages are a great way to get the user’s immediate attention, no matter what they are currently doing.  Some of you are probably wondering how we make these updates from a Background task, and for you, I ask for patience.  We wanted to make sure we gave a solid overview of each of these notification types before we dove headfirst into Background tasks.  You’re only two days away from that topic, I promise.

If you would like to download the entire code solution for this article, click the icon below:

downloadXAML

Tomorrow, we’ll cover our last topic in the notifications world, Lock Screen.  See you then!

downloadTheTools

Related Posts:


Published at DZone with permission of Jeff Blankenburg, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)