添加計劃的Toast
Toast是在螢幕角上的“toast”視窗中出現的訊息。不論計劃toast的應用是否正在運行,Toast都會出現。Toast可由應用自行計劃(在應用啟動並執行時候),也可以在響應Windows通知服務的通知時顯示。而且,toast中除了文本之外,還可以包含聲音。
在這個練習中,您要向Contoso Cookbook添加一個toast,類比一個提醒。
任務1 – 修改應用程式欄
為了提供計劃toast的使用者介面,我們要給應用程式欄添加一個“Reminder”命令。
1. 開啟default.html,找到ID為“appbar”的DIV元素。
2. 在聲明“Pin-Recipe”命令後的DIV中添加以下語句,給應用程式欄增加一個“Reminder”:
HTML
<buttondata-win-control="WinJS.UI.AppBarCommand"data-win-options="{id:'remind', label:'Reminder', icon:'',section: 'selection'}"></button>
3. 開啟itemDetailPage.js,在ready函數中找到“appbar.showOnlyCommands”。
4. 將這條語句改為下面這樣:
JavaScript
appbar.showOnlyCommands(["photo","video", "pin", "remind", "home"]);
5. 啟動應用程式,點擊一個菜譜,開啟項目詳細資料頁面。
6. 確認應用程式欄中包含“Reminder”命令,5所示。
圖5
“Reminder”命令
7. 返回VisualStudio並停止調試。
任務2 – 計劃一個Toast
下面為“Reminder”命令編寫點擊事件處理器,用它來計劃一個toast。
1. 在方案總管的js檔案夾上點擊右鍵,用“Add - New Item”命令在檔案夾中添加名為notifications.js的JavaScript檔案。
2. 在notifications.js中添加以下代碼:
JavaScript
(function () {
"use strict";
var toast = Windows.UI.Notifications;
WinJS.Namespace.define("notifications",{
// Schedules a toast notification
scheduleToast: function () {
// Create a toast notifier
varnotifier =toast.ToastNotificationManager.createToastNotifier();
// Make sure notifications are enabled
if (notifier.setting != toast.NotificationSetting.enabled) {
var dialog = newWindows.UI.Popups.MessageDialog("Notifications are currentlydisabled");
dialog.showAsync();
return;
}
// Get a toast template and insert a text node containing a message
var template =toast.ToastNotificationManager.getTemplateContent(toast.ToastTemplateType.toastText01);
var element =template.getElementsByTagName("text")[0];
element.appendChild(template.createTextNode("Reminder!"));
// Schedule the toast to appear 30 seconds from now
var date = new Date(new Date().getTime() +30000);
varstn =toast.ScheduledToastNotification(template, date);
notifier.addToSchedule(stn);
}
});
})();
3. 在default.html中添加以下SCRIPT元素:
HTML
<scriptsrc="/js/notifications.js"></script>
4. 在default.html中,將以下高亮顯示內容添加到“Reminder”命令:
HTML
<buttondata-win-control="WinJS.UI.AppBarCommand"data-win-options="{id:'remind', label:'Reminder', icon:'',section: 'selection',onclick: notifications.scheduleToast}"></button>
5. 在測試之前的最後一項工作,就是在清單中啟用toast通知,開啟package.appxmanifest,並在“Application UI”選項卡中將“Toast Capable”設定改為“Yes”(圖6)。
圖6
啟用toast通知
注意:必須先啟用“Toast Capable”,應用才能計劃toast。啟用這一設定後,會在應用的許可頁面上出現一個切換按鈕,允許使用者開戶或關閉。剛剛添加的scheduleToast函數可以檢查通知是否啟用,如果未啟用,則向使用者發出警告。
任務3 – 計劃一個Toast!
最後一項任務是,測試代碼,計劃一個toast,並查看toast的效果。
1. 按F5啟用應用程式。
2. 開啟選中的菜譜。
3. 顯示應用程式欄,點擊“Reminder”按鈕。
4. 切換到Metro開始畫面或其他應用,等待大約30秒,toast就會出現(圖7)。
圖7
Contoso Cookbook的toast
5. 點擊toast視窗,確認切換回了Contoso Cookbook。
6. 返回VisualStudio並停止調試。
注意:本文章為msdn上windows8線上實驗的指令碼,僅供學習參考。如果想體驗完整實驗可以點擊以下msdn的線上實驗室
http://msdn.microsoft.com/zh-cn/hh968278