In my last post I introduced Toast Notifications for WinRT apps. In that example I had the notification show immediately, but you can also schedule a toast to appear sometime in the future. The NotificaitonsExtensions library doesn’t have direct support for scheduled toast but this is pretty easy to work around.
Here is the code for a scheduled toast:
var toast = ToastContentFactory.CreateToastText01(); toast.TextBodyWrap.Text = "You have a new message"; var schedToast = new ScheduledToastNotification(toast.GetXml(), DateTime.Now.AddSeconds(30), new TimeSpan(0, 0, 60), 5); ToastNotificationManager.CreateToastNotifier().AddToSchedule(schedToast);
The first two lines setup a toast notification using the NotificationsExtensions library just like we did in the last example. In the next line we create the scheduled toast object, by passing four parameters to the constructor. For the first parameter we use the GetXml() function to get the XML template from our toast object. The second parameter sets the time when we want the toast to appear, in this case 30 seconds in the future. The third and fourth parameters are optional and allow you to enable the snooze capability of the notification. When the user closes the toast it will reappear after the time interval set in the third parameter (this must be from 60 seconds to 60 minutes), and will reappear the number of time in the fourth parameter (this must be from 1 to 5).
The final line calls the AddToSchedule function to schedule the notification.
Once the notification has been created it will pop up at the scheduled time even if the program is no longer in memory. There is a function called RemoveFromSchedule that can be used to remove the notification if you have still have a reference to the ScheduledToastNotification object. In most cases we won’t still have a reference to this object so we need a way to find it. To do this we will first have to add a unique identifier to the ScheduledToastNotification object:
schedToast.Id = "ToastID1";
Here I am just using a fixed string, but for a real application you will have to come up with some method of uniquely identifying notifications. After the notification has been created you can use the Id to find and remove it:
var scheduled = ToastNotificationManager.CreateToastNotifier().GetScheduledToastNotifications(); foreach( ScheduledToastNotification notify in scheduled) { if (notify.Id == "ToastID1") ToastNotificationManager.CreateToastNotifier().RemoveFromSchedule(notify); }
In this code the first line gets a list of all scheduled toast notifications that our app has created. The next two lines will iterate through this collection looking for the Id of the notification we want to remove, then calling RemoveFromSchedule to remove it.
1 comment:
Your articles are purely enough for me.
Florida
Post a Comment