在你發送應用程式通知後,當通知不再相關時,你可能需要將它從通知中心移除,或控制它持續的時間長短。 AppNotificationManager 類別提供移除通知的方法,AppNotification 類別則提供控制通知自動到期時間的屬性。
欲了解更多關於應用程式通知的資訊,請參閱 應用程式通知總覽。
移除通知中心的通知
要移除特定通知,先在顯示時指定標籤和群組值。 標籤用 來識別特定的 通知, 而群組 則用來識別一組相關的通知。 例如,一個訊息應用程式可以用聊天串的 ID 作為 群組 ,聯絡人名稱作為 標籤。
AppNotificationManager 提供多種方法來移除通知中心的通知:
| 方法 | 說明 |
|---|---|
| 異步按標籤移除 | 移除所有帶有指定標籤的通知。 |
| RemoveByGroupAsync | 移除指定群組中的所有通知。 |
| RemoveByTagAndGroupAsync | 移除所有帶有指定標籤和群組的通知。 |
| 移除ByIdAsync | 移除包含指定 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();
}
設定到期時間
如果內容只在一定期間內相關,請使用 「到期 」屬性設定通知的有效期限。 例如,一個發送事件提醒的行事曆應用程式應該將到期日設為事件結束。
備註
通知的預設及最長有效期限為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);