次の方法で共有


Quickstart: Sending a toast notification (XAML)

Note  Not using C#/VB/C++? See Quickstart: Sending a toast notification (HTML).

 

A toast notification is a pop-up UI that appears on your screen to allow your app to communicate with the user when the user is in another app, on the Start screen, or, in the case of Windows, on the desktop. This Quickstart walks you through the steps to define and display toast content. These actions are demonstrated through a local notification, which is the simplest notification to implement. We discuss the following steps:

  • Specifying a template for your notification
  • Retrieving the template's blank XML content
  • Adding text to the notification
  • Adding an image to the notification
  • Setting a duration for your notification
  • Specifying audio to accompany your notification
  • Providing contextual information used when your app is activated by the notification
  • Sending your toast as a local notification

Note  In this Quickstart you'll manipulate the notification content directly through the XML Document Object Model (DOM). An optional approach is available through the NotificationsExtensions library, which presents the XML content as object properties, including Intellisense. For more information, see Quickstart: Using the NotificationsExtensions library in your code. To see the code in this Quickstart expressed using NotificationsExtenstions, see the Toast notifications sample.

 

Note  When testing toast notification code functionality through Microsoft Visual Studio, you must use either the Local Machine or Remote Machine debug setting on a Windows x86, x64, or Windows Runtime machine. You cannot use the Visual Studio Simulator debug function option—your code will compile and run in the Simulator, but the toast will not appear.

 

Prerequisites

To understand this topic, you will need:

  • A working knowledge of toast notification terms and concepts. For more information, see Toast overview.
  • A working knowledge of general notification terms and concepts. For more information, see Sending notifications.
  • A familiarity with the toast XML schema as well as a general familiarity with XML and its manipulation through Document Object Model (DOM) APIs. For more information, see Toast schema.
  • The ability to create a basic Windows Store app with C# or C++ Microsoft Visual Basic using Windows Runtime APIs, and an understanding of how to create a code-behind in those languages for a Windows Store app with Extensible Application Markup Language (XAML). For more information, see Create your first Windows Store app using C# or Visual Basic.

Also, you must have declared in your app's manifest that it is capable of receiving toast notifications. For more information, see How to opt in for toast notifications.

Instructions

1. Add namespace declarations

Windows.UI.Notifications includes the toast APIs.

using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
using namespace Windows::UI::Notifications;
using namespace Windows::Data::Xml::Dom;

2. Pick a template for your toast and retrieve its XML contents

Choose a template from the system-provided template catalog that fits the needs of your content. For the complete list of templates, see the ToastTemplateType enumeration. Note that each separate notification that you send can use a different template.

Note  Only a variation of the toastText02 template is supported on Windows Phone 8.1. It accepts two text strings, with the first rendered in bold text, but they are both on the same line so only one short string or two very short strings should be used to avoid concatenation.

This example, for use with Windows, uses the ToastImageAndText01 template, which requires one image and one string of text. An example is shown here:

ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText01; 
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
ToastTemplateType toastTemplate = ToastTemplateType::ToastImageAndText01; 
XmlDocument^ toastXml = ToastNotificationManager::GetTemplateContent(toastTemplate);

The GetTemplateContent method returns an XmlDocument. The code above retrieves the following XML skeleton, for which you will provide the details in subsequent steps through standard DOM functions:

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

3. Supply text content for your notification

This example first retrieves all elements in the template with a tag name of "text". The ToastImageAndText01 template contains only a single text string, which the code assigns. This string can wrap over a maximum of three lines, so the length of the string should be set accordingly to avoid truncation.

   
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode("Hello World!"));
XmlNodeList^ toastTextElements = toastXml->GetElementsByTagName("text");
toastTextElements->Item(0)->InnerText = "Hello World!";

4. Supply an image for your notification

This code first retrieves all elements in the template with a tag name of "image". A toast template, such as toastImageAndText01, contains at most one image. Note that not all toast templates contain images; some are text only.

XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");
XmlNodeList^ toastImageAttributes = toastXml->GetElementsByTagName("image");

Images can be used from the app's package, the app's local storage, or from the web. Versions of this step are shown for each image source. Images must be less than 200 KB in size and smaller than 1024 x 1024 pixels. For more information, see Tile and toast image sizes.

The following code uses a local image from the app's package. This type of image is included in your Visual Studio solution file and is packaged as part of your app. These images are accessed by using the "ms-appx:///" prefix. As a best practice, we also assign optional alt text for accessibility purposes such as screen readers.

Important  The image "redWide.png" used here is only an example and is not included in a Microsoft Visual Studio project. You will need to replace "redWide.png" with the name of an actual image of your own that you've added to the project before you attempt to send this toast.

 

((XmlElement)toastImageAttributes[0]).SetAttribute("src", "ms-appx:///assets/redWide.png");
((XmlElement)toastImageAttributes[0]).SetAttribute("alt", "red graphic");
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("src", "ms-appx:///assets/redWide.png");                        
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("alt", "red graphic");

The following code uses a local image from the app's local storage. This type of image has been saved by your app to its local storage. This is the location returned by Windows.Storage.ApplicationData.Current.LocalFolder. These images are accessed by using the "ms-appdata:///local/" prefix. Again, we also assign optional alt text for accessibility purposes such as screen readers.

((XmlElement)toastImageAttributes[0]).SetAttribute("src", "ms-appdata:///local/redWide.png");
((XmlElement)toastImageAttributes[0]).SetAttribute("alt", "red graphic");
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("src", "ms-appdata:///local/redWide.png");                        
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("alt", "red graphic");

The following code uses a web image. These images are accessed by using the "http://" protocol to specify the image's path. You can also use the "https://" protocol.

((XmlElement)toastImageAttributes[0]).SetAttribute("src", "https://www.contoso.com/redWide.png");
((XmlElement)toastImageAttributes[0]).SetAttribute("alt", "red graphic");
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("src", "https://www.contoso.com/redWide.png");                        
static_cast<XmlElement^>(toastImageAttributes->Item(0))->SetAttribute("alt", "red graphic");

You can use the optional baseUri attribute to specify a root path, such as "https://www.contoso.com/", that is combined with any relative Uniform Resource Identifiers (URIs) specified in any image's src attributes. This attribute can be set on either the visual element (to apply to the entire notification) or the binding element (to apply to that binding). If baseUri is set on both, the value in binding overrides the value in visual.

If the baseUri was set to "https://www.contoso.com/", this line in the example code:

((XmlElement)toastImageAttributes[0]).SetAttribute("src", "https://www.contoso.com/redWide.png");

could be shortened to this:

((XmlElement)toastImageAttributes[0]).SetAttribute("src", "redWide.png");

5. Optional: Specify a toast duration

You can optionally set a display duration for your toast. There are two values: "short" (the default) and "long". Use "long" only if your notification is part of a scenario such as an incoming call or appointment reminder. For more information, see Toast notification overview.

Note  Different durations are not supported on Windows Phone 8.1; all toasts have the same duration. If this attribute is included in a phone toast notification, it is ignored.

Note  The default duration is "short", so you normally would add this attribute only to set the duration to "long".

 

IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "long");
IXmlNode^ toastNode = toastXml->SelectSingleNode("/toast");
static_cast<XmlElement^>(toastNode)->SetAttribute("duration", "long");

6. Optional: Specify toast audio

For more information on toast audio, see The toast audio options catalog.

By default, Windows plays a short sound when your toast is displayed. You can optionally specify a different sound from a system-provided set of sounds, or no sound at all. On Windows Phone 8.1, you can specify a custom sound. For more information, see The toast audio options catalog.

A template retrieved through getTemplateContent does not contain an audio element, so you must define and add it to your XML payload. The sound file is specified by using the "ms-winsoundevent:" prefix, or, on Windows Phone 8.1, a path that uses the "ms-appx:///" or "ms-appdata:///" prefix. This example creates an audio element and selects the toast element that will be its parent.

IXmlNode toastNode = toastXml.SelectSingleNode("/toast");                        
XmlElement audio = toastXml.CreateElement("audio");
IXmlNode^ toastNode = toastXml->SelectSingleNode("/toast");
XmlElement^ audio = toastXml->CreateElement("audio");

This example specifies a non-default sound.

audio.SetAttribute("src", "ms-winsoundevent:Notification.IM");
audio->SetAttribute("src", "ms-winsoundevent:Notification.IM");

This example specifies that no sound should play.

audio.SetAttribute("silent", "true");
audio->SetAttribute("silent", "true");

In the case of a long-duration toast notification, the sound can be looped rather than playing only once. Note that looping audio is only valid for long-duration toasts. Specific sounds for use with looping are included in the system-specified sound set. This example specifies a looping sound.

Note  Because it does not support long-duration toasts, Windows Phone 8.1 does not support looped audio.

((XmlElement)toastNode).SetAttribute("duration", "long");

audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Alarm");
audio.SetAttribute("loop", "true");
static_cast<XmlElement^>(toastNode)->SetAttribute("duration", "long");

audio->SetAttribute("src", "ms-winsoundevent:Notification.Looping.Alarm");
audio->SetAttribute("loop", "true");

Once you have defined your audio element, you must attach it to your toast's XML payload as a child of the toast element, as shown here.

toastNode.AppendChild(audio);
toastNode->AppendChild(audio);

7. Specify app launch parameters

When the user clicks your toast notification, the expectation is that your app will be launched, with a view that relates to the content of the notification. To accomplish this, use the launch attribute of the toast element, which provides a string that is passed from the toast to the app when the app is launched through the toast. This string has no specific form and is app-defined. Your app must check for this string as an argument each time that it is activated adjust its view or operation accordingly.

((XmlElement)toastNode).SetAttribute("launch", "{\"type\":\"toast\",\"param1\":\"12345\",\"param2\":\"67890\"}");
static_cast<XmlElement^>(toastNode)->SetAttribute("launch", "{\"type\":\"toast\",\"param1\":\"12345\",\"param2\":\"67890\"}");

Note  In Windows Phone Silverlight 8.1, the value of the launch string is appended to your default launch page's URI. For example, if you provide the launch string "?conversation=71", it results in a URI such as /MainPage.xaml?conversation=71. Therefore, the launch string must also be a valid query string; otherwise, an exception is thrown.

8. Create the toast notification based on the XML content you've specified.

ToastNotification toast = new ToastNotification(toastXml);
ToastNotification^ toast = ref new ToastNotification(toastXml);

9. Send your toast notification.

ToastNotificationManager.CreateToastNotifier().Show(toast);
ToastNotificationManager::CreateToastNotifier()->Show(toast);

Note  In Windows Phone Silverlight 8.1, a toast is not displayed if the current foreground app is the caller of the ToastNotifier.Show method. In that case, toast should primarily be used by a background agent.

Note: For Windows Store apps, The background color applied to your toast notification is the background color declared for your app's tile in its app manifest. For more information, see Quickstart: Creating a default tile using the Visual Studio manifest editor.

Summary and next steps

In this Quickstart, your sent your local toast notification to your user.

This Quickstart sent the toast as a local notification, that being the simplest notification type to implement and allowing you to quickly see your results. Next, you should explore the other methods of toast notification delivery: scheduled and push. For more information, see Delivering notifications.

Samples

Toast notifications sample

Sending toast notifications from desktop apps sample

Reversi sample feature scenarios: toast notifications

Conceptual

Toast notification overview

The toast template catalog

The toast audio options catalog

Instructional

Quickstart: Sending a push notification

How to handle activation from a toast notification

How to opt in for toast notifications

How to schedule a toast notification

Quickstart: Sending a toast notification from the desktop

How to enable desktop toast notifications through an AppUserModelID

Best practices

Guidelines and checklist for toast notifications

Reference

Toast XML schema

ToastNotification

ToastNotificationManager

ToastNotifier