There is one other type of notification that I didn’t cover in my original articles on WinRT application notification, that is the toast notification. In this article I will explain how to use these with the NotficationsExtensions that I introduced in my last post.
Unlike tile notifications and badges, toast notifications show up in the application UI instead of on the start screen tile, and will even show up if they user is in a different app. The notification tile appears on the upper right corner of the screen and will stay visible for a short period of time or until the user closes it.
Before we can show toast notifications there are a couple things we need to do. First, open the Package.appmanifest in your application and be sure Toast capable is set to Yes.
Next, on the start screen select Settings from the Charm menu, click Change PC Setting, then select Notifications and be sure Show app notification is turned on
Now we can look at the code. First be sure you have the NotificationsExtensions library included in your application as I described in my last post. You will also want to add these two namespaces:
using NotificationsExtensions.ToastContent; using Windows.UI.Notifications;
Here is the code to display a simple notification.
var toast = ToastContentFactory.CreateToastText01(); toast.TextBodyWrap.Text = "You have a new message"; var notify = toast.CreateNotification(); ToastNotificationManager.CreateToastNotifier().Show(notify);
The first line uses the NotificationsExtensions library to create an object for the notification template we want to use. Just like notification tiles on the Start menu there are a number of different notification styles, some with text and some with text and an image. Once we have the template object we can set the text we want to display, this is done in the second line. Finally the third and fourth lines display the notification which will stay on the screen for about seven seconds then fade out.
If you want it to stay on the screen longer you can do this to have it displayed for 25 seconds:
toast.Duration = ToastDuration.Long;
This is a simple example of a notification, but there are other things we can do with it. When the notification popped up you will notice that there was a sound along with it. You can change this sound to one of a couple different built in sounds like this:
toast.Audio.Content = ToastAudioContent.Reminder;
or you can turn it off completely like this:
toast.Audio.Content = ToastAudioContent.Silent;
Instead of a single short sound, you can also specify one of a series of looping sounds that will play until the toast disappears or is dismissed.
toast.Duration = ToastDuration.Long; toast.Audio.Loop = true; toast.Audio.Content = ToastAudioContent.LoopingCall;
For the looping sounds to work you also have to have the Duration set to Long and the Loop property set to true.