安排通知app

你可以安排 app 通知在稍後時間出現,不論當時 app 是否在運行。 這對於顯示提醒或其他後續任務等情境非常有用,因為通知的時間與內容事先已知。

排程 app 通知的送達時段為5分鐘。 若電腦在預定配送時間內關機,且關機超過5分鐘,通知將因與使用者無關而「中斷」。 如果你需要無論電腦關機多久都能保證收到通知,我們建議使用帶有時間觸發器的背景任務。 更多資訊請參閱 背景任務。

欲了解更多通知 app 資訊,請參閱 App 通知總覽。

備註

本文的程式碼範例使用 Microsoft.Windows.AppNotifications 命名空間來建立通知內容,並使用 Windows.UI.Notifications 命名空間來排程。 這兩個命名空間可以同時用於同一個 app。

排程通知

若要排定未來通知,請使用 AppNotificationBuilder 定義通知內容,然後撥打 AddToSchedule,並附上 ScheduledToastNotification。 以下範例預定通知會在 10 秒後出現。

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

var payload = new AppNotificationBuilder()
    .AddArgument("action", "viewItemsDueToday")
    .AddText("ASTR 170B1")
    .AddText("You have 3 items due today!")
    .BuildNotification()
    .Payload;

var doc = new XmlDocument();
doc.LoadXml(payload);

var scheduledNotification = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddSeconds(10));
scheduledNotification.Tag = "18365";
scheduledNotification.Group = "ASTR 170B1";

ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledNotification);

標籤與群組屬性作為通知的複合主鍵。 設定這些值後,您可以取消或替換排程通知,如下節所示。

取消已排定的通知

要取消排程通知,請呼叫 GetScheduledToastNotifications 取得待處理通知清單,接著對你先前指定的標籤呼叫 RemoveFromSchedule 。

var notifier = ToastNotificationManager.CreateToastNotifier();
var scheduled = notifier.GetScheduledToastNotifications();

foreach (var notification in scheduled)
{
    if (notification.Tag == "18365")
    {
        notifier.RemoveFromSchedule(notification);
    }
}

另請參閱