应用通知集合

在通知中心使用集合来组织应用的通知。 集合可帮助用户更轻松地查找信息,并允许开发人员更好地管理其通知。

例如,消息传递应用可以通过聊天组分隔通知。 每个组标题(“计算机科学 160A 项目聊天”、“私信”、“Lacrosse 团队聊天”)都是一个单独的集合。 通知被分组得像来自一个单独的应用程序,即使它们都来自同一应用。 有关组织通知的更微妙的方法,请参阅 应用通知标头

具有两组不同通知的集合示例

注释

本文中的代码示例使用 Microsoft.Windows.AppNotifications 命名空间生成通知内容和用于集合管理的 Windows.UI.Notifications 命名空间。 这两个命名空间可以一起使用在同一应用中。

有关应用通知的详细信息,请参阅 应用通知概述

创建集合

创建集合时,提供显示名称和图标,该图标显示在通知中心作为集合标题的一部分。 集合还需要启动参数,以便在用户单击集合标题时,应用可以导航到正确的位置。 通过调用 SaveToastCollectionAsync 创建集合。

using Windows.UI.Notifications;

var collection = new ToastCollection(
    "MyToastCollection",
    "Work Email",
    "NavigateToWorkEmailInbox",
    new Uri("ms-appx:///Assets/workEmail.png"));

await ToastNotificationManager.GetDefault()
    .GetToastCollectionManager()
    .SaveToastCollectionAsync(collection);

将通知发送到数据集合

使用 AppNotificationBuilder 构造通知内容,然后调用 GetToastNotifierForToastCollectionIdAsync 以获取作用域为集合的通知器。

using Microsoft.Windows.AppNotifications.Builder;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

// Build notification content with Windows App SDK
var payload = new AppNotificationBuilder()
    .AddText("Adam sent a message to the group")
    .BuildNotification()
    .Payload;

// Deliver to a collection using the WinRT API
var doc = new XmlDocument();
doc.LoadXml(payload);
var toast = new ToastNotification(doc);

var notifier = await ToastNotificationManager.GetDefault()
    .GetToastNotifierForToastCollectionIdAsync("MyToastCollection");
notifier.Show(toast);

列出所有集合

通过调用 FindAllToastCollectionsAsync 检索为应用创建的所有集合。

var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();
var collections = await collectionManager.FindAllToastCollectionsAsync();

更新集合

通过使用相同的 ID 创建新的 ToastCollection 实例并调用 SaveToastCollectionAsync 来更新集合。

var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();

var updatedCollection = new ToastCollection(
    "MyToastCollection",
    "Updated Display Name",
    "UpdatedLaunchArgs",
    new Uri("ms-appx:///Assets/updatedPicture.png"));

await collectionManager.SaveToastCollectionAsync(updatedCollection);

删除集合

通过使用集合 ID 调用 RemoveToastCollectionAsync 来 删除集合。 集合中的任何通知也会从通知中心中删除。

var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();
await collectionManager.RemoveToastCollectionAsync("MyToastCollection");

删除集合中的通知

使用 标记 属性通过调用 Remove 来识别和删除集合中的单个通知,或使用 Clear 同时清除所有通知。

var collectionHistory = await ToastNotificationManager.GetDefault()
    .GetHistoryForToastCollectionAsync("MyToastCollection");

// Remove a specific notification
collectionHistory.Remove(tag, group);

// Or clear all notifications in the collection
collectionHistory.Clear();

另见