应用通知是显示在应用窗口外部的 UI 弹出窗口,向用户提供及时的信息或操作。 通知可以纯粹是信息性的,可以在单击时启动应用,也可以触发后台操作,而无需将应用引入前台。
本文将引导你完成从 UWP 应用创建和发送应用通知的步骤,然后在用户与其交互时处理激活。
有关其他框架的应用通知和指南的概述,请参阅 应用通知概述。
本文介绍本地通知。 有关从云服务传送通知的信息,请参阅 推送通知概述。
先决条件
- Visual Studio中的 UWP 应用项目
- 安装在 Visual Studio 中的 通用 Windows 平台 开发工作负荷
发送应用通知
UWP 应用使用 Windows.UI.Notifications 命名空间来使用 XML 构造和发送通知。 本部分介绍如何使用 C# 和 C++ 发送通知。
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
var xml = @"<toast launch=""action=viewConversation&conversationId=9813"">
<visual>
<binding template=""ToastGeneric"">
<text>Andrew sent you a picture</text>
<text>Check this out, The Enchantments in Washington!</text>
</binding>
</visual>
</toast>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var notification = new ToastNotification(doc);
ToastNotificationManager.CreateToastNotifier().Show(notification);
处理激活操作
当用户单击您的通知(或具有前台激活功能的通知按钮)时,应用的OnActivated方法将被调用。
OnLaunched 不调用通知激活,即使应用已关闭且首次启动。 我们建议将 OnLaunched 和 OnActivated 组合成一个共享的初始化方法。
App.xaml.cs
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
OnLaunchedOrActivated(e.PreviousExecutionState);
var rootFrame = Window.Current.Content as Frame;
if (e.PrelaunchActivated == false)
{
if (rootFrame?.Content == null)
{
rootFrame?.Navigate(typeof(MainPage), e.Arguments);
}
Window.Current.Activate();
}
}
protected override void OnActivated(IActivatedEventArgs e)
{
OnLaunchedOrActivated(e.PreviousExecutionState);
if (e is ToastNotificationActivatedEventArgs toastArgs)
{
var rootFrame = Window.Current.Content as Frame;
if (rootFrame?.Content == null)
{
rootFrame?.Navigate(typeof(MainPage));
}
Window.Current.Activate();
// Parse the notification arguments
string argument = toastArgs.Argument;
// TODO: Navigate to the relevant content based on the arguments
}
}
private void OnLaunchedOrActivated(ApplicationExecutionState previousState)
{
if (Window.Current.Content is not Frame)
{
var rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Window.Current.Content = rootFrame;
}
}
有关向通知添加按钮、图像、输入、音频和其他丰富内容的信息,请参阅 应用通知内容。