快速入门:Windows 应用 SDK 中的应用通知

一张屏幕截图显示任务栏上方的应用通知。该通知是一个事件提醒,显示应用名称、事件名称、事件时间和事件地点。选择框显示当前选定的值“参加”。有两个按钮标记为“RSVP”和“忽略”

在本快速入门中,你将使用 Windows 应用 SDK创建一个桌面 Windows 应用程序,该应用程序发送和接收本地应用通知(也称为 toast 通知)。

Important

当前不支持管理员权限应用的通知。

Prerequisites

Sample app

本快速入门介绍了 GitHub上发现的 通知示例应用的代码。

API reference

有关应用通知的 API 参考文档,请参阅 Microsoft.Windows.AppNotifications 命名空间

步骤 1:添加命名空间声明

Microsoft.Windows.AppNotifications添加 Windows 应用 SDK 应用通知的命名空间。

using Microsoft.Windows.AppNotifications;

步骤 2:更新应用的清单文件

如果应用已解压缩(即运行时缺少包标识),请跳到 步骤 3:注册以处理应用通知

如果应用已打包(包括使用外部位置打包):

  1. 打开 Package.appxmanifest
  2. xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" 命名空间添加到 <Package>
  3. <desktop:Extension> 添加 windows.toastNotificationActivation,以声明 COM 激活器 CLSID。 可以通过在 Visual Studio 中的 工具 下导航到 创建 GUID 来获取 CLSID。
  4. 使用相同的 CLSID 为 COM 激活器添加 <com:Extension>
    1. Executable 属性中指定 .exe 文件。 注册应用程序以接收通知时,涉及 .exe 文件的过程必须与调用 Register() 时的过程一致,具体细节在 步骤 3中有更详细的描述。 在下面的示例中,我们使用 Executable="SampleApp\SampleApp.exe"
    2. 指定 Arguments="----AppNotificationActivated:" 以确保 Windows 应用 SDK 可以将通知的有效负载作为 AppNotification 类型进行处理。
    3. 指定 DisplayName

Important

警告:如果在 appx 清单中使用 定义 <uap:Protocol> 应用扩展性类型,则即使应用已在运行,单击通知也会启动同一应用的新进程。

<!--Packaged apps only-->
<!--package.appxmanifest-->

<Package
  xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"
  xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
  ...
  <Applications>
    <Application>
      ...
      <Extensions>

        <!--Specify which CLSID to activate when notification is clicked-->   
        <desktop:Extension Category="windows.toastNotificationActivation">
          <desktop:ToastNotificationActivation ToastActivatorCLSID="replaced-with-your-guid-C173E6ADF0C3" />
        </desktop:Extension>

        <!--Register COM CLSID-->    
        <com:Extension Category="windows.comServer">
          <com:ComServer>
            <com:ExeServer Executable="SampleApp\SampleApp.exe" DisplayName="SampleApp" Arguments="----AppNotificationActivated:">
              <com:Class Id="replaced-with-your-guid-C173E6ADF0C3" />
            </com:ExeServer>
          </com:ComServer>
        </com:Extension>
    
      </Extensions>
    </Application>
  </Applications>
 </Package>

步骤 3:注册以处理应用通知

注册应用以处理通知,然后在应用终止时注销。

App.xaml 文件中,注册 AppNotificationManager::Default().NotificationInvoked,然后调用 AppNotificationManager::Default().Register。 这些调用的顺序很重要。

Important

必须先调用 AppNotificationManager::Default().Register,然后再调用 AppInstance.GetCurrent.GetActivatedEventArgs

当应用终止时,请调用 AppNotificationManager::Default().Unregister() 以释放 COM 服务器,并允许后续调用启动新进程。

// App.xaml.cs
namespace CsUnpackagedAppNotifications
{

    public partial class App : Application
    {
        private Window mainWindow;
        private NotificationManager notificationManager;
        
        public App()
        {
            this.InitializeComponent();
            notificationManager = new NotificationManager();
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            mainWindow = new MainWindow();

            notificationManager.Init();
            
            // Complete in Step 5
            
            mainWindow.Activate();
        }

        void OnProcessExit(object sender, EventArgs e)
        {
            notificationManager.Unregister();
        }
    }
}


// NotificationManager.cs
namespace CsUnpackagedAppNotifications
{
    internal class NotificationManager
    {
        private bool m_isRegistered;

        private Dictionary<int, Action<AppNotificationActivatedEventArgs>> c_map;

        public NotificationManager()
        {
            m_isRegistered = false;

            // When adding new a scenario, be sure to add its notification handler here.
            c_map = new Dictionary<int, Action<AppNotificationActivatedEventArgs>>();
            c_map.Add(ToastWithAvatar.ScenarioId, ToastWithAvatar.NotificationReceived);
            c_map.Add(ToastWithTextBox.ScenarioId, ToastWithTextBox.NotificationReceived);
        }

        ~NotificationManager()
        {
            Unregister();
        }

        public void Init()
        {
            // To ensure all Notification handling happens in this process instance, register for
            // NotificationInvoked before calling Register(). Without this a new process will
            // be launched to handle the notification.
            AppNotificationManager notificationManager = AppNotificationManager.Default;

            notificationManager.NotificationInvoked += OnNotificationInvoked;

            notificationManager.Register();
            m_isRegistered = true;
        }

        public void Unregister()
        {
            if (m_isRegistered)
            {
                AppNotificationManager.Default.Unregister();
                m_isRegistered = false;
            }
        }

        public void ProcessLaunchActivationArgs(AppNotificationActivatedEventArgs notificationActivatedEventArgs)
        {
            // Complete in Step 5
        }

    }
}       

步骤 4:显示应用通知

应用通知使用按钮

在继续之前,您 必须 完成 步骤 3:注册以处理应用通知

现在,你将显示一个简单的应用通知,其中包含一个 appLogoOverride 图像和一个按钮。

使用 AppNotificationBuilder 类构造应用通知,然后调用 Show。 有关如何使用 XML 构造应用通知的详细信息,请参阅 Toast 内容通知 XML 架构的示例。

Note

如果应用已打包(包括使用外部位置打包),则通知左上角中的应用图标源自 package.manifest。 如果应用已解压缩,则首先查看快捷方式,然后查看应用进程中的资源文件,从而生成图标。 如果所有尝试都失败,则使用 Windows 默认应用图标。 支持的图标文件类型为 .jpg.png.bmp.ico

// ToastWithAvatar.cs
class ToastWithAvatar
{
    public const int ScenarioId = 1;
    public const string ScenarioName = "Local Toast with Avatar Image";

    public static bool SendToast()
    {
        var appNotification = new AppNotificationBuilder()
            .AddArgument("action", "ToastClick")
            .AddArgument(Common.scenarioTag, ScenarioId.ToString())
            .SetAppLogoOverride(new System.Uri("file://" + App.GetFullPathToAsset("Square150x150Logo.png")), AppNotificationImageCrop.Circle)
            .AddText(ScenarioName)
            .AddText("This is an example message using XML")
            .AddButton(new AppNotificationButton("Open App")
                .AddArgument("action", "OpenApp")
                .AddArgument(Common.scenarioTag, ScenarioId.ToString()))
            .BuildNotification();

        AppNotificationManager.Default.Show(appNotification);

        return appNotification.Id != 0; // return true (indicating success) if the toast was sent (if it has an Id)
    }

    public static void NotificationReceived(AppNotificationActivatedEventArgs notificationActivatedEventArgs)
    {
        // Complete in Step 5   
    }
}

// Call SendToast() to send a notification. 

步骤 5:处理用户选择通知

用户可以选择通知的正文或按钮。 应用需要处理调用,以响应与通知交互的用户。

可通过 2 种常见方法来处理此问题:

  1. 您选择在特定的 UI 上下文中启动应用程序或
  2. 您可以选择让应用在不呈现任何用户界面的情况下,评估特定操作行为(例如通知正文中的按钮按下)。 也称为后台操作。

下面的代码示例(不是来自示例应用)演示了处理用户生成的操作的两种方式。 将 launch 值(对应于用户单击通知正文)、input 元素(快速答复文本框),以及具有 arguments 值的按钮(对应于用户单击该按钮)的按钮添加到通知的 XML 有效负载。 在 ProcessLaunchActivationArgs中,针对每个参数进行分析。

Important

对于桌面应用,将忽略通知 XML 负载中的设置 activationType="background"。 必须处理激活参数,并决定是否显示窗口,如本步骤中所述。

回复 的应用通知

// Example of how to process a user either selecting the notification body or inputting a quick reply in the text box. 

// Notification XML payload
//<toast launch="action=openThread&amp;threadId=92187">
//  <visual>
//      <binding template="ToastGeneric">
//          <image placement="appLogoOverride" hint-crop="circle" src="C:\<fullpath>\Logo.png"/>
//          <text>Local Toast with Avatar and Text box</text>
//          <text>This is an example message using</text>
//      </binding>
//  </visual>
//  <actions>
//      <input id="replyBox" type="text" placeHolderContent="Reply" />
//      <action
//          content="Send"
//          hint-inputId="replyBox"
//          arguments="action=reply&amp;threadId=92187" />
//  </actions>
//</toast>

void ProcessLaunchActivationArgs(const winrt::AppNotificationActivatedEventArgs& notificationActivatedEventArgs)
{
    // If the user clicks on the notification body, your app needs to launch the chat thread window
    if (std::wstring(notificationActivatedEventArgs.Argument().c_str()).find(L"openThread") != std::wstring::npos)
    {
        GenerateChatThreadWindow();
    }
    else // If the user responds to a message by clicking a button in the notification, your app needs to reply back to the other user with no window launched
    if (std::wstring(notificationActivatedEventArgs.Argument().c_str()).find(L"reply") != std::wstring::npos)
    {
        auto input = notificationActivatedEventArgs.UserInput();
        auto replyBoxText = input.Lookup(L"replyBox");

        // Process the reply text
        SendReplyToUser(replyBoxText);
    }
}

遵循以下准则

  1. 如果用户选择了通知并且你的应用未运行,则预期你的应用已启动,并且用户可以在通知的上下文中看到前台窗口。
  2. 如果用户选择了通知,并你的应用程序处于最小化状态,那么预期是你的应用程序会被带到前台,并在与通知相关的上下文中打开一个新窗口。
  3. 如果用户调用通知后台操作(例如用户通过在通知文本框中键入并点击回复来响应通知),则应用将处理有效负载而不呈现前台窗口。

有关更详细的示例,请参阅 GitHub 上找到的示例应用代码。

步骤 6:删除通知

当通知不再与用户相关时,请删除它们。

在此示例中,用户已看到应用中群组聊天中的所有消息,因此你可以清除群组聊天中的所有通知。 然后,用户将朋友设为静音,以便清除好友的所有通知。 首先将 标记 属性添加到通知中,然后再显示通知,以便现在可以识别它们。


void SendNotification(winrt::hstring const& payload, winrt::hstring const& friendId, winrt::hstring const& groupChatId)
{
    winrt::AppNotification notification(payload);

    // Setting Group Id here allows clearing notifications from a specific chat group later
    notification.Group(groupChatId);

    // Setting Tag Id here allows clearing notifications from a specific friend later
    notification.Tag(friendId);

    winrt::AppNotificationManager::Default().Show(notification);
}

winrt::Windows::Foundation::IAsyncAction RemoveAllNotificationsFromGroupChat(const std::wstring groupChatId)
{
    winrt::AppNotificationManager manager = winrt::AppNotificationManager::Default();
    co_await manager.RemoveByGroupAsync(groupChatId);    
}

winrt::Windows::Foundation::IAsyncAction RemoveAllNotificationsFromFriend(const std::wstring friendId)
{
    winrt::AppNotificationManager manager = winrt::AppNotificationManager::Default();
    co_await manager.RemoveByTagAsync(friendId);    
}

Additional features

发送云源应用通知

若要从云发送应用通知,请按照 快速入门 发送云源应用通知:在 Windows 应用 SDK推送通知。

设置过期时间

如果通知中的消息仅与特定时间段相关,请使用 Expiration 属性在应用通知上设置过期时间。 例如,如果发送日历事件提醒,请将过期时间设置为日历事件的结束时间。

Note

默认和最长过期时间为 3 天。

class ToastWithAvatar
{
    public static bool SendToast()
    {

        var appNotification = new AppNotificationBuilder()
            .SetAppLogoOverride(new System.Uri("ms-appx:///images/logo.png"), AppNotificationImageCrop.Circle)
            .AddText("Example expiring notification")
            .AddText("This is an example message")
            .BuildNotification();


        appNotification.Expiration = DateTime.Now.AddDays(1);
        AppNotificationManager.Default.Show(appNotification);

        return appNotification.Id != 0; // return true (indicating success) if the toast was sent (if it has an Id)
    }
}

确保通知在重新启动时过期

如果要在重新启动时删除通知,请将 ExpiresOnReboot 属性设置为 True

class ToastWithAvatar
{
    public static bool SendToast()
    {

        var appNotification = new AppNotificationBuilder()
            .SetAppLogoOverride(new System.Uri("ms-appx:///images/logo.png"), AppNotificationImageCrop.Circle)
            .AddText("Example ExpiresOnReboot notification")
            .AddText("This is an example message")
            .BuildNotification();


            appNotification.ExpiresOnReboot = true;
            AppNotificationManager.Default.Show(appNotification);

            return appNotification.Id != 0; // return true (indicating success) if the toast was sent (if it has an Id)
    }
}

发送和更新进度栏通知

可以在通知中显示进度栏相关更新:

带有进度栏的 通知

使用 AppNotificationProgressData 构造更新进度栏通知。

const winrt::hstring c_tag = L"weekly-playlist";
const winrt::hstring c_group = L"downloads";

// Send first Notification Progress Update
void SendUpdatableNotificationWithProgress()
{
    auto notification{ winrt::AppNotificationBuilder()
            .AddText(L"Downloading this week's new music...")
            .AddProgressBar(winrt::AppNotificationProgressBar()
                .BindTitle()
                .BindValue()
                .BindValueStringOverride()
                .BindStatus())
            .BuildNotification() }

    notification.Tag(c_tag);
    notification.Group(c_group);

    // Assign initial values for first notification progress UI
    winrt::AppNotificationProgressData data(1); // Sequence number
    data.Title(L"Weekly playlist"); // Binds to {progressTitle} in xml payload
    data.Value(0.6); // Binds to {progressValue} in xml payload
    data.ValueStringOverride(L"15/26 songs"); // Binds to {progressValueString} in xml payload
    data.Status(L"Downloading..."); // Binds to {progressStatus} in xml payload

    notification.Progress(data);
    winrt::AppNotificationManager::Default().Show(notification);
}

// Send subsequent progress updates
winrt::Windows::Foundation::IAsyncAction UpdateProgressAsync()
{
    // Assign new values
    winrt::AppNotificationProgressData data(2 /* Sequence number */ );
    data.Title(L"Weekly playlist"); // Binds to {progressTitle} in xml payload
    data.Value(0.7); // Binds to {progressValue} in xml payload
    data.ValueStringOverride(L"18/26 songs"); // Binds to {progressValueString} in xml payload
    data.Status(L"Downloading..."); // Binds to {progressStatus} in xml payload

    auto result = co_await winrt::AppNotificationManager::Default().UpdateAsync(data, c_tag, c_group);
    if (result == winrt::AppNotificationProgressResult::AppNotificationNotFound)
    {
        // Progress Update failed since the previous notification update was dismissed by the user! So account for this in your logic by stopping updates or starting a new Progress Update flow.
    }
}

Resources