HTML5 Zone is brought to you in partnership with:

Clark is a web evangelist for Microsoft based in Illinois. A Chicago native who can’t spell, Clark as a kid actually made his money building cars, getting grease under his nails. That art of building would later lead him to software development where he drinks the Web Development Kool-Aid. Writing code is what keeps Clark awake at night, while continually working on his craft and rapping with others over a few cold CORS. You can hear Clark muse about software on his podcast Developer Smackdown, or find his family cruising around in a 1968 Camaro SS. Clark is a DZone MVB and is not an employee of DZone and has posted 32 posts at DZone. You can read more from them at their website. View Full User Profile

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

11.15.2012
| 3633 views |
  • submit to reddit

XAMLCallout

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.

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. Yummy. 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.  By default in the top right hand corner. 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 exampleToastImageAndText01 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.

image

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 and I am not going to go into the same amount of detail here.  Just like live tiles there is an xml schema which represents the toast we want to send, note <toast>.

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

As we did with Live Tiles, we do the same or very  similar with toast. 

  • Get an instance of WinRT Notification
  • From Notifications, get your Template
  • From that Template, get it’s content aka that XML we showed above
  • Select and Update appropriately
  • (optional) set your duration
  • (optional) set audio
  • (optional) set any app launch parameters
  • Create a new tile notification
  • Send tile update
    var notifications = Windows.UI.Notifications;
    
    var template = notifications.ToastTemplateType.toastImageAndText02;
    var toastXml = notifications.ToastNotificationManager.getTemplateContent(template);
    
    var toastTextElements = toastXml.getElementsByTagName("text");
    toastTextElements[0].innerText = "31 Days of Windows 8";
    toastTextElements[1].innerText = _toastMessage.value; //taking from screen
    
    var toastImageElements = toastXml.getElementsByTagName("image");
    toastImageElements[0].setAttribute("src", "ms-appx:///images/clarkHeadShot.jpg");
    toastImageElements[0].setAttribute("alt", "Clark's Head");
    
    var toast = new notifications.ToastNotification(toastXml);
    var toastNotifier = notifications.ToastNotificationManager.createToastNotifier();
    toastNotifier.show(toast);

As you can see this is scary similar to Live Tiles. I am setting two text properties, and one image property.  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(toast) 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:

 image

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 excluded code for creating a Toast notification ( just look above ) and just added the part where we would modify the template to add our audio clip.

....

var toastNode = toastXml.selectSingleNode("/toast");

var audio = toastXml.createElement("audio");
audio.setAttribute("src", "ms-winsoundevent:Notification.IM");
toastNode.appendChild(audio);

....

You an also set the duration, how long it will stay on the screen for a piece of Toast.

....

var toastNode = toastXml.selectSingleNode("/toast");
toastNode.setAttribute("duration", "long");

....

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:

var audio = toastXml.createElement("audio");
audio.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.

....

var toastXml = notifications.ToastNotificationManager.getTemplateContent(template);

...

toastXml.selectSingleNode("/toast").setAttribute("launch", '{
                "type":"toast",
                "args1":"31days",
                "args2":"#10"}' );

....

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, we 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:

downloadHTMLdownloadTheTools

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




Published at DZone with permission of Clark Sell, 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.)