Blog Feed Post

Windows 8 Notifications: Programmatic Concepts

Windows reimaginedIn my previous blog post, I provided a high level overview of notifications in Window 8, breaking the functionality down in terms of the user experience (tiles, toast, and badges) and delivery mechanisms (local, scheduled, periodic, and push). This post will look at the common programmatic concepts of the user experience: what you can do with tiles, toast and badges, and how you accomplish that within code. Subsequent blogs posts will focus more deeply on the specific delivery mechanisms.

What is a Notification?

At its very core a notification is simply a bit of information you wish to convey to the user, and it’s the Windows 8 runtime that provides a framework for both how and when the notifications appear. Regardless of the user experience, the structure of a notification is provided via an XML template. There are predefined templates for tile, toast and badge notifications, and every notification must comply with one of these templates.

Below is an overview of the templates for each of the user interface elements (tiles, toast, and badges) along with a visual sample and the XML template that is used for that sample. The highlighted sections within the samples below indicate what you as a developer must modify to create the element. Follow the associated view schema links (in the first column) to find other options such as how to enhance a toast notification with audio and how to format the image src attribute to indicate where an image is hosted: web, local storage, or in the app package itself.

Table I. Visual Notification Types Summary

Type Options Sample UI and Template

(view schema)
Sample toast notification
      <binding template="ToastImageAndText02"> 
         <image id="1" src="img.png" alt="image1"/> 
         <text id="1">MarketLimit Order Reached</text> 
         <text id="2">You just sold 200 shares of MSFT at $32.50</text> 

(view schema)
Sample tile notification
      <binding template="TileWideImageCollection"> 
         <image id="1" src="image1.png" alt="alt text"/> 
         <image id="2" src="image2.png" alt="alt text"/>        
         <image id="3" src="image3.png" alt="alt text"/> 
         <image id="4" src="image4.png" alt="alt text"/> 
         <image id="5" src="image5.png" alt="alt text"/> 

(view schema)

Sample badge notification

<badge value=”7” />

There’s a great deal of similarity for handling the notification content regardless of the type (tile, toast or badge), and the next few sections map out that workflow and provide pointers and links to the various notification classes that are relevant at each stage of the process.  Be sure to check out the links in the green callout as well for guidance on how and when (and when not) to incorporate the various notification types in your application.

  1. Accessing the Notification Template
  2. Customizing Template Content
  3. Sending the Notification
  4. Responding to the Notification
MSDN Notification Guidelines and Checklists

Lastly, I’ll close the post with an admittedly hodgepodge section of other important concepts and features you should be aware of as you plan out your application’s notification strategy.

1. Accessing the Notification Template

Every notification type has an associated ‘manager’ class that can be used to access the available templates, each of which has a well-known name. In quasi-JavaScript the code follows the pattern:

var manager = manager_type;
var xmlTemplate = manager_type.getTemplateContent(template_type);

where the italicized JavaScript class placeholders associated with each notification type are itemized in the following table (you can get to the C++, C#, and VB analogs from these links as well).

Table II. Notification Manager and Template Classes

Notification Type manager-type template_type (enumeration)
Toast ToastNotificationManager ToastTemplateType
Tile TileUpdateManager TileTemplateType
Badge BadgeUpdateManager BadgeTemplateType

To access the template for the stock purchase toast notification shown earlier in this post, the following code would be used:

// use 'n' as namespace shortcut
var n = Windows.UI.Notifications;
var manager = n.ToastNotificationManager;
var xmlTemplate = manager.getTemplateContent(n.ToastTemplateType.toastImageAndText02);

2. Customizing Template Content

With the XML template (of type XmlDocument) in hand, you can use the various XML DOM methods to replace the elements (images, text, etc.) with customized data, for example:

var txt = xmlTemplate.getElementsByTagName("text");
txt[0].appendChild(xmlTemplate.createTextNode("Market Limit Order Reached"));
"You just sold 200 shares of MSFT at $32.50"));
var img = xmlTemplate.getElementsByTagName("image")[0];
img.setAttribute("src", "http://jimoneil.blob.core.windows.net/tiles/stock.jpg");

That’s not hard code to write, but it’s hard to get it right! Navigating the XML DOM makes for some tedious and error prone programming, so you’ll be happy to know there’s another, more strongly-typed, way to go about this.

The Toast notifications Sample (and perhaps others) on the Windows Dev Center includes a C# project called NotificationExtensions that you can incorporate into your own projects to provide a set of strongly typed classes with the appropriate properties for each type of toast, badge, or tile notification. Instead of manipulating the DOM, you can write code like the following:

var content = ToastContent.ToastContentFactory.createToastImageAndText02();
content.textHeading.text = "Market Limit Order Reached";
content.textBodyWrap.text = "You just sold 200 shares of MSFT at $32.50";
content.image.src = "http://jimoneil.blob.core.windows.net/tiles/stock.jpg";

Be aware though that the content variable above is NOT an XML type, but an abstraction of it. There is a method you'll eventually call to convert it into the XML type before sending the notification.

Windows AzureBy the way, did you notice the URL for the image? It’s a live URL – I’m guessing you already tried it out – hosted in a blob storage account in the cloud. It turns out Windows Azure is a great option for hosting various bits of content to serve up in your application, particularly images and other information appearing in notifications.

3. Sending the Notification

How you send the notification depends on the delivery mechanism, and while most of that discussion will be deferred to subsequent posts, I don’t want to leave you hanging! Recall that earlier I mentioned each UI notification type has an associated ‘manager’ class, and you use that class to retrieve the XML template for the notification. That manager class is also the entry point into sending the notification, regardless of the delivery mechanism. It’s a three step process:

  1. Create a notification instance from the formatted XML template using one of the constructors in the second column of Table III below. (If you used the NotificationExtensions helper class, the CreateNotification method available on the INotificationContent instance will yield a notification instance).
  2. Obtain a notifier class instance by invoking one of the factory methods (third column of Table III) on the desired notification type’s manager class (namely, ToastNotificationManager, TileUpdateManager, or BadgeUpdateManager)
  3. Table III. Notification and Notifier Instantiation Methods.

    Notification Type Notification Instance Constructor Notifier Class Factory Methods
    Toast ToastNotification
    Tile TileNotification
    Badge BadgeNotification createBadgeUpdaterForApplication
  4. Invoke the method (in Table IV) on the notifier class instance (obtained in step 2) corresponding to the desired delivery mechanism, passing in the notification instance that was created in step 1. You’ll note there is no “Push” column here, and that’s because your code will react to the arrival of a push notification, but it won’t initiate the request; I’ll discuss those details in a dedicated future post on push notifications.

    Table IV. Notification Delivery Methods

    Notification Type Notifier Class Notifier Class Method (by delivery mechanism)
    Local Scheduled Periodic
    Toast ToastNotifier show addToSchedule  
    Tile TileUpdater update addToSchedule startPeriodicUpdate
    Badge BadgeUpdater update   startPeriodicUpdate

The complete code for sending the stock purchase toast notification would then look like the following; the two lines of code that send the local notification are highlighted to complete this simple end-to-end JavaScript snippet.

// use 'n' as namespace shortcut
var n = Windows.UI.Notifications;
var manager = n.ToastNotificationManager;
var xmlTemplate = manager.getTemplateContent(n.ToastTemplateType.toastImageAndText02);

var txt = xmlTemplate.getElementsByTagName("text");
txt[0].appendChild(xmlTemplate.createTextNode("Market Limit Order Reached"));
"You just sold 200 shares of MSFT at $32.50")); var img = xmlTemplate.getElementsByTagName("image")[0]; img.setAttribute("src", "http://jimoneil.blob.core.windows.net/tiles/stock.jpg");
var toast = n.ToastNotification(xmlTemplate);

4. Responding to the Notification

In the case of toast notifications specifically, the arrival of the notification may implicitly prompt the user to click on it (such as to accept an incoming VOIP call), so you will likely want to include code in your application to respond to the interaction and open your application to a context consistent with the notification. For example, if a user clicks on the stock sale toast sample I’ve been using, he might expect the associated trading application to open right to a page with the trade confirmation details. Providing such an experience requires two main capabilities:

  • Additional context must be available for the application to know what to display when activated. That context is typically provided via the launch attribute of the toast tag in the template for that toast. The attribute is a string, the format and contents of which are left up to the application developer’s discretion (though JSON is an obvious choice for an HTML/JS application).
  • The application must be able to respond to events on the toast notification itself; there are two options:
    • Implement events provided on the ToastNotification class
      1. activated fires when the clicks or touches the toast notification (but only for local notifications!)
      2. dismissed fires when the user closes the toast or it expires from the screen
      3. failed fires when there’s an error displaying the toast
    • Implement the onactivated event of the main application class, WinJS.Application (or the OnLaunched event of the Application class for C++, VB, and C#) to handle any type of toast delivery mechanism.

4.1 Providing Application Launch Context

Continuing with the stock sale notification, I can provide launch context to the notification by adding the following to the template customization code (prior to showing the toast, of course).

var tst= xmlTemplate.getElementsByTagName("toast")[0];
tst.setAttribute("launch", '{ "confirmation" : "20120717000123" }');

4.2 Application’s Response to Launch Request

When the toast comes in and the user clicks on it, the application may or may not be running, but in either case the application class will respond to a launch activation request. In response, your code can check why the application was activated – for a notification activation, you’d be looking for the argument to that callback to have a detail property of kind WebUILaunchActivatedEventArgs.

Next, you’d pull the ‘launch’ arguments from the arguments property of that same detail object, and use those values to influence the navigation – for instance, showing a stock sale transaction statement for a given confirmation id.

The code for this (below) may initially be a bit intimidating, but only because it’s part of the activation handling flow for the entire application.

  • Line 4 is where it’s determined if the request is for a launch, one of the triggers for which is a toast notification.
  • If there’s a payload of additional context (e.detail.arguments isn’t empty in Line 5), that’s a cue to do something special when launching.
  • In Line 8, the confirmation number (if there is one) is extracted from the payload. By the way, you should treat the contents as untrusted data, so include safeguards in your application to validate data and guard from injection attacks.
  • The code checks in Line 11 if there really was a confirmation number in that JSON, and if so navigates to a specific order confirmation page.
  • The confirmation is passed as an argument (Line 12), so presumably the code for that page will query a database or other services to pull in the information specific for that stock sale notification.
  • If it turns out it’s not a toast notification of a sale confirmation that activated the application, then the app will simply navigate to the last page it was at (saved as part of the sessionState) or go to the default opening page of the app (Lines 16-17).
   1:  // in default.js
   2:  function activated(e) {
   3:      e.setPromise(WinJS.UI.processAll().then(function () {
   4:          if (e.detail.kind === 
   5:              && e.detail.arguments !== "") {
   7:             // parse out the confirmation number
   8:              var confNumber = JSON.parse(e.detail.arguments)["confirmations"];
  10:             // if it's there, navigate to the specific confirmation page
  11:              if (typeof confNumber !== 'undefined')
  12:                 return WinJS.Navigation.navigate(confPage.url, confNumber);
  13:          } 
  15:          // otherwise do the default navigation
  16:          var url = WinJS.Application.sessionState.lastUrl || homePage.url;
  17:          return WinJS.Navigation.navigate(url);
  18:      }));
  19:  }
  21:     ...
  23:  // wire up handler
  24:  WinJS.Application.addEventListener("activated", activated, false);
  25:  WinJS.Application.start();

Advanced Topics

The post thus far should get you well on your way to setting up notifications within your applications, but to provide that added extra touch to your users’ experience, there are a few additional items I want to bring to your attention. I won’t go into as much detail as above, since the documentation covers these topics well, but it’s important to know the various options that exist so you can incorporate them into your design as appropriate.

Tile Sizes

End users have control over whether or not your application’s tile shows as a square or wide (rectangular) one. Wide tiles are useful for more lengthy content like e-mail or social medial updates or perhaps photo and media applications. You don’t have to provide a rectangular tile option, however, if you do provide it, you cannot assume that will the size the user has displayed at any given time.

If you do opt for wide tiles, be sure that your notifications include both wide and square templates (as separate binding elements). If you neglect to send a template of the appropriate size, and the user has configured her start screen contrary to what you are sending, she will not see the notification.

Also be aware that if your application provides the user the option to display its detailed status on the Lock screen, you must also send a wide tile notification.

Secondary Tiles

Above you probably noticed earlier in Table III, there are two methods to get a TileUpdater for tile notifications, one associated with the main application tile and one associated with a secondary tile. A secondary tile provides a customized experience for an application that’s already installed.

For instance, you might have a weather application installed, but want to see the weather for both your current location as well as home. If that weather application exposes the ability to create a secondary tile (typically via a “Pin to Start” option on the app bar), you could have two tiles available on the desktop associated with the same application. The secondary tile, when created, has a unique tileID and arguments that can be interpreted by the application to open to the appropriate context and allow notifications to target a specific tile.

Notification queue

By default, each time a new tile notification arrives, the previous notification is replaced; however, by enabling the notification queue you can have a tile cycle through up to five notifications (for instance, display stock quotes for five different ticker symbols). You can also assign tags (arbitrary labels of up to 16 characters) to each notification, and rather than pushing out the oldest notification in the queue, the runtime will replace an existing notification bearing the same tag with the new content.

You can enable the notification queue via the EnableNotificationQueue method of the TileUpdater class, and for periodic updates the startPeriodicUpdateBatch method is available to provide up to five URIs that correspond to the content to be cycled.

Stopping Notifications

One thing that may surprise you is that it’s just as important (if not more important) to plan out when to stop or remove notifications, and there are certainly APIs to facilitate handling scenarios such as the following:

  • Tiles expire after three days by default. Consider what happens if a user is disconnected for a couple of hours or even days; the last tile update that arrived will be the only one he continues to see – does that makes sense in the context of your application? or should you set a shorter (or longer) expirationTime? should you clear the tile at some point?
  • Also consider what happens if you have a scheduled notification in play but the event of interest is no longer relevant (e.g., your application’s user sent regrets for a meeting she previously accepted but can no longer attend) – your application probably needs to call removeFromSchedule.
  • Or what if you’re leveraging periodic notifications, where the content is being controlled by a third party and that third party is no longer providing content? You’ll likely want to stopPeriodicUpdate for the badge (or tile notification) that’s in play.
  • You may also want to hide push notifications based on the application context. For instance, Outlook brings up toast when a new e-mail comes in, but only if it doesn’t have focus. If I’m viewing my inbox, I can see that a new e-mail came in, and toast is superfluous and perhaps a bit annoying. The pushNotificationReceived event provides the control needed to handle situations like this.

Long-running Toast

The XML schema for toast provides a duration attribute controlling then length of time a toast appears on screen

  • short duration toasts (the default) are displayed for 7 seconds, and
  • long duration toasts are displayed for 25 seconds.

Long duration toasts are appropriate when the notification requires additional setup or time to respond. For instance, you’d  want a VOIP request to ‘ring’ for a while on the recipient’s machine to catch her attention and give her time to connect her headset.

Lock Screen

Windows 8, via the PC Settings option accessible from the Settings charm, allows the user to select up to seven applications for which an application icon and badge are displayed on the start screen (as shown in the yellow lasso below). Additionally, the user can select one application for which detailed text from the current tile is displayed (shown circled in red below).Lock Screen

To support these options, you’ll need to

  • provide a monochrome white 24x24 icon Badge Logo as part of your application manifest, and
  • a wide tile binding for the tile corresponding to the application for which detailed text should be displayed.  Note that images from a wide tile are not displayed here, so ensure that the text can stand on its own and not require an image to disambiguate it.

There is no additional processing needed on the application developer’s part, since the Lock screen will automatically reflect the current state of the tile associated with those applications promoted there by the user.

Image Sizes and Formats

Windows 8 runs on a wide array of devices of different size and resolutions, so ‘it works on my machine’ isn’t enough to guarantee a great experience for all of your application users. Be cognizant of image size and scale requirements, namely

Note that when a notification references invalid content, it most cases it will simply just not appear, and that’s a difficult outcome to diagnose!

Read the original blog entry...

More Stories By Jim O'Neil

Jim is a Technology Evangelist for Microsoft who covers the Northeast District, namely, New England and upstate New York. He is focused on engaging with the development community in the area through user groups, code camps, BarCamps, Microsoft-sponsored events, etc., and just in general serve as ambassador for Microsoft. Since 2009, Jim has been focusing on software development scenarios using cloud computing and Windows Azure. You can follow Jim on Twitter at @jimoneil

Latest Stories
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
"We're developing a software that is based on the cloud environment and we are providing those services to corporations and the general public," explained Seungmin Kim, CEO/CTO of SM Systems Inc., in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, discussed how data centers of the future will be managed, how the p...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...