2012年8月3日 星期五

ToastNotification

通常沒有很重要的提示訊息,用 MessageBox 還要用戶自己關閉就太擾人了,
在 Android 上有個 Toast 可以用來通知用戶簡單的訊息,
Windows Phone 上也有 ToastNotification,但必須由背景觸發,頗麻煩,
好在 Windows  8 的 ToastNotification 不論 App 在前景、背景都可以正常顯示。

官方文件可以參考:ToastNotification
範例可以參考:Toast notifications sample
其實這次感興趣的是範例中的 NotificationExtensions Project
在 MSDN 中還有一篇特地在介紹這個 Project:Using NotificationsExtensions
這個專案可以很方便的讓開發者以簡單的指令建立 XmlDocument
可以使用的樣板就如官方文件中所示的全部:ToastTemplateType enumeration
假設我們想要建立一個有圖片、三行文字的 Toast 就可以選用 ToastImageAndText04
使用 NotificationExtensions 幫我們產生 Toast 的範例如下…

IToastNotificationContent toastContent = null;
IToastImageAndText04 templateContent = ToastContentFactory.CreateToastImageAndText04();
templateContent.TextHeading.Text = "Heading text";
templateContent.TextBody1.Text = "Body text";
templateContent.TextBody2.Text = "Another body text";
templateContent.Image.Src = "http://a.b.c/test.png";
toastContent = templateContent;

ToastNotification toast = toastContent.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(toast);

NotificationExtensions 專案提供很好的封裝讓開發者輕易的設定 Toast 內容,
若我們不想要將這個專案加入自己的 App 中其實也可以自行產生 XML
只要照著 Toast 需要的 XML Schema 產生 XmlDocument 即可達到一樣的效果
Tile、Toast、Badge 的 Schema 在這裡可以找到:Tiles, toast, and badge schemas
一樣使用 ToastImageAndText04 這個樣板來示範,程式碼的量多了不少…

// 目標是產生此結構的 XmlDocument
//<toast>
//    <visual version='1'>
//        <binding template='ToastImageAndText04'>
//            <image id='1' src='http://a.b.c/test.png'/>
//            <text id='1'>Heading text</text>
//            <text id='2'>Body text</text>
//            <text id='3'>Another body text</text>
//        </binding>
//    </visual>
//</toast>

XmlDocument doc = new XmlDocument();
// 建立 toast 根節點
XmlElement toast = doc.CreateElement("toast");
doc.AppendChild(toast);
// 在 toast 內建立 visual 節點
XmlElement visual = doc.CreateElement("visual");
visual.SetAttribute("version", "1");
toast.AppendChild(visual);
// 在 visual 內建立 binding 子節點,並指定使用 ToastImageAndText04 樣板
XmlElement binding = doc.CreateElement("binding");
binding.SetAttribute("template", "ToastImageAndText04");
visual.AppendChild(binding);
// 在 binding 內放入三個樣板所需的元件節點
XmlElement image = doc.CreateElement("image");
image.SetAttribute("id", "1");
image.SetAttribute("src", "http://a.b.c/test.png");
binding.AppendChild(image);
XmlElement text1 = doc.CreateElement("text");
text1.SetAttribute("id", "1");
text1.InnerText = "Heading text";
binding.AppendChild(text1);
XmlElement text2 = doc.CreateElement("text");
text2.SetAttribute("id", "2");
text2.InnerText = "Body text";
binding.AppendChild(text2);
XmlElement text3 = doc.CreateElement("text");
text3.SetAttribute("id", "3");
text3.InnerText = "Another body text";
binding.AppendChild(text3);

ToastNotification toastNotification = new ToastNotification(doc);
ToastNotificationManager.CreateToastNotifier().Show(toastNotification);


比較起來使用 NotificationExtensions 實在方便許多,
而且它也提供了很好的機會讓一般初學者看看如何規劃封裝類別庫的過程。

沒有留言:

張貼留言