アプリの通知を削除する

アプリ通知を送信した後、関連がなくなったときに通知センターから削除するか、保持期間を制御することが必要になる場合があります。 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);

こちらも参照ください