定期预定的Toastnotification UWP

时间:2017-11-25 14:18:14

标签: c# notifications uwp

我想创建定期的通知,但我找到了一个不正确的解决方案,因为snoozeInterva只是一个"推迟"。

代码:

public sealed partial class MainPage : Page
{
    const string TOAST = @"
                        <toast>
                          <visual>
                            <binding template=""ToastTest"">
                              <text>Hello Toast</text>
                            </binding>
                          </visual>
                          <audio src =""ms-winsoundevent:Notification.Mail"" loop=""true""/>
                        </toast>";

    public MainPage()
    {
        this.InitializeComponent();
    }

    private void btnNotification_Click(object sender, RoutedEventArgs e)
    {
        var when = DateTime.Now.AddSeconds(6);
        var offset = new DateTimeOffset(when);

        Windows.Data.Xml.Dom.XmlDocument xml = new Windows.Data.Xml.Dom.XmlDocument();
        xml.LoadXml(TOAST);
        ScheduledToastNotification toast = new ScheduledToastNotification(xml, offset, TimeSpan.FromSeconds(60), 5);
        toast.Id = "IdTostone";
        toast.Tag = "NotificationOne";
        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
    }
}

那么..我怎样才能创建定期的吐司通知,例如每天13:00?

提前致谢!

1 个答案:

答案 0 :(得分:0)

不幸的是,没有方便的方法可以做到这一点。如果你需要每天同时发送一个祝酒词,你可以安排一堆吐司通知,比如说,提前一个月,每天一个。然后,如果您需要更改所有这些祝酒词的当天时间,可以使用ToastNotificationManager类从吐司时间表中删除它们,并在合适的时间创建新的预定祝酒词。

这样的事情:

    private void ScheduleToast(DateTime scheduledTime)
    {
        const string TOAST = @"
                    <toast>
                      <visual>
                        <binding template=""ToastTest"">
                          <text>Hello Toast</text>
                        </binding>
                      </visual>
                      <audio src =""ms-winsoundevent:Notification.Mail"" loop=""true""/>
                    </toast>";

        Windows.Data.Xml.Dom.XmlDocument xml = new Windows.Data.Xml.Dom.XmlDocument();
        xml.LoadXml(TOAST);

        ScheduledToastNotification toast = new ScheduledToastNotification(xml, scheduledTime);
        toast.Id = "IdTostone" + scheduledTime.ToString();
        toast.Tag = "NotificationOne";
        toast.Group = "MyEverydayToasts";
        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
    }

    private void RescheduleToastsForTheNextDays(TimeSpan timeOfDay, int nDays = 30)
    {
        ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();
        IReadOnlyList<ScheduledToastNotification> scheduledToasts = toastNotifier.GetScheduledToastNotifications();
        foreach(ScheduledToastNotification toast in scheduledToasts)
            toastNotifier.RemoveFromSchedule(toast);

        for (int i=0; i<nDays; i++)
        {
            DateTime scheduledTime = DateTime.Today + timeOfDay + TimeSpan.FromDays(i);

            if (scheduledTime > DateTime.Now)
                ScheduleToast(scheduledTime);
        }
    }