发送应用通知后,可能需要在通知中心不再相关时将其删除,或控制其保留时间。 AppNotificationManager 类提供用于删除通知的方法,AppNotification 类提供用于控制通知过期时间的属性。
有关应用通知的详细信息,请参阅 应用通知概述。
从通知中心删除通知
若要删除特定通知,请在显示它们时先分配 标记 值和 组 值。 标记标识特定通知,组标识一组相关通知。 例如,消息应用可以使用聊天线程 ID 作为 组 ,并将联系人姓名用作 标记。
AppNotificationManager 提供了几种从通知中心删除通知的方法:
| 方法 | 说明 |
|---|---|
| RemoveByTagAsync | 删除具有指定标记的所有通知。 |
| RemoveByGroupAsync | 删除指定组中的所有通知。 |
| RemoveByTagAndGroupAsync | 删除具有指定标记和组的所有通知。 |
| RemoveByIdAsync | 删除具有指定 ID 的通知。 |
| RemoveAllAsync | 删除应用的所有通知。 |
以下示例演示如何在发送通知时标记通知,然后稍后将其删除。 在此方案中,消息应用在用户读取聊天后从群组聊天中删除所有通知,然后在用户静音后从特定联系人中删除所有通知。
using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;
void SendNotification(string message, string contactTag, string chatGroup)
{
var notification = new AppNotificationBuilder()
.AddText(message)
.BuildNotification();
// Tag and group the notification so it can be removed later
notification.Tag = contactTag;
notification.Group = chatGroup;
AppNotificationManager.Default.Show(notification);
}
// Remove all notifications from a specific group chat
async Task RemoveGroupChatNotifications(string chatGroup)
{
await AppNotificationManager.Default.RemoveByGroupAsync(chatGroup);
}
// Remove all notifications from a specific contact across all groups
async Task RemoveContactNotifications(string contactTag)
{
await AppNotificationManager.Default.RemoveByTagAsync(contactTag);
}
// Remove all notifications for the app
async Task RemoveAllNotifications()
{
await AppNotificationManager.Default.RemoveAllAsync();
}
设置过期时间
如果内容仅与特定时间段相关,则使用 Expiration 属性设置通知的过期时间。 例如,发送事件提醒的日历应用应将过期时间设置为事件结束。
注释
通知的默认和最长过期时间为 3 天。
using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;
var notification = new AppNotificationBuilder()
.AddText("Team standup in 15 minutes")
.AddText("Conference Room B")
.BuildNotification();
// Remove the notification from Notification Center after one hour
notification.Expiration = DateTimeOffset.Now.AddHours(1);
AppNotificationManager.Default.Show(notification);
在重新启动时使通知失效
如果希望在计算机重启时从通知中心中删除通知,请将 ExpiresOnReboot 属性设置为 true ” 重启后不再有意义的时间敏感通知(例如正在进行的通话或临时提醒)会非常有用。
using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;
var notification = new AppNotificationBuilder()
.AddText("You're sharing your screen")
.BuildNotification();
notification.ExpiresOnReboot = true;
AppNotificationManager.Default.Show(notification);