2014年9月22日 星期一

使用 NotificationsExtensions 建立 Toast Notification

現在應用程式的使用流程愈來愈傾向於盡量的少打擾使用者,Toast Notification 就是一種用來通知用戶事件發生又沒什麼干擾性的方法,建立 Toast Notification 的最基本方式是利用 XML 描述 Toast 的 Layout 並利用 ToastNotificationManager 來顯示,而 XML 的內容結構可以參考這裡:Tiles, toast, and badge schemas

因為撰寫組成 XML 的程式碼太陽春了,所以可以透過 NuGet 安裝 NotificationsExtensions 來幫助我們做這件事,這個 Library 提供了一些 Factory 讓開發者快速的產生 Toast、Tile、Badge,官方的文件可以參考這裡:Using the NotificationsExtensions library in your code

在使用 NuGet 安裝 NotificationsExtensions 時若是使用搜尋需特別注意 Microsoft 的官方版本除了 NotificationsExtensions 之外,還會找到另一個叫 NotificationsExtensions.WinRT 的官方版本,這是給 Windows Runtime 框架的 Win8 App 使用的,內容有些差異會無法讓 Windows Phone Project 使用,若是要撰寫 Universal Apps 那裝 Created by Microsoft 的那個 NotificationsExtensions 就對了。

以下撰寫一段簡單的例子來產生通知,這段 Code 在 Windows Store App 上與 Windows Phone Store App 上寫法是一模一樣的,但顯示的樣式是不同的,Windows Phone 上沒有包含圖片的功能 ( 測試時,記得將 Package.appxmanifest 中的 Toast capable 設為 Yes )

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    var toastContent = NotificationsExtensions.ToastContent.ToastContentFactory.CreateToastImageAndText01();
    toastContent.TextBodyWrap.Text = "Lorem ipsum dolor sit amet";
    toastContent.Image.Src = "http://aaa.bbb.ccc/Toast.png";
    toastContent.Image.Alt = "A red rectangle";
    toastContent.Audio.Content = NotificationsExtensions.ToastContent.ToastAudioContent.LoopingAlarm;
    toastContent.Audio.Loop = true;
    toastContent.Duration = NotificationsExtensions.ToastContent.ToastDuration.Long;
    var toast = toastContent.CreateNotification();
    Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier().Show(toast);
}

上面的範例使用了 ToastImageAndText01 這種樣式,除了這個之外還有許多 Toast 的樣式,可以參考以前 Windows Runtime 的官方文件:ToastTemplateType enumeration

如果只需要撰寫 Windows Store Apps 也可以安裝 NotificationsExtensions.WinRT 函式庫,使方法大致上也是利用 Factory 來建立各種外型的 Toast 例如

/*
以下程式碼僅能在 Windows RT 中正常編譯
*/
private void OnButtonClick(object sender, RoutedEventArgs e)
{
    IToastNotificationContent toastContent = null;
    IToastImageAndText02 templateContent = ToastContentFactory.CreateToastImageAndText02();
    templateContent.TextHeading.Text = "Heading text";
    templateContent.TextBodyWrap.Text = "Body text that wraps.";
    templateContent.Image.Src = "http://aaa.bbb.ccc/toast.png";
    templateContent.Image.Alt = "Alt";
    toastContent = templateContent;
    ToastNotification toast = toastContent.CreateNotification();
    ToastNotificationManager.CreateToastNotifier().Show(toast);
}



沒有留言:

張貼留言