Windows Phone 8.1 - Toast Notification事件與Action Center

Windows Phone 8.1 - Toast Notification事件與Action Center

<Windows Phone 8.1 - 操作Toast Notification>介紹Toast Notification組合結構、傳遞方式與相關Schema的定義與操作,

這一篇再介紹Toast Notification幾個重要的元素,以及Action Center如何來操作。

 

複習一下發送Toast Notification的程式片段:

private void SendToast()
{
    XmlDocument tXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
    //加入text1 與 text2
    XmlNodeList tTextNodes = tXml.GetElementsByTagName("text");
    tTextNodes[0].AppendChild(tXml.CreateTextNode("Text1"));
    tTextNodes[1].AppendChild(tXml.CreateTextNode("Text2"));
 
    //指定<audio />
    IXmlNode tToastNode = tXml.SelectSingleNode("/toast");
    XmlElement tAudio = tXml.CreateElement("audio");
    tAudio.SetAttribute("src", "ms-winsoundevent:Notification.Reminder");
    tAudio.SetAttribute("loop", "false");
    //設定靜音
    //tAudio.SetAttribute("silent", "true");
    tToastNode.AppendChild(tAudio);
 
    //指定Launch的參數,param1與param2是自定的
    //((XmlElement)tToastNode).SetAttribute("launch", 
    //            "{\"type\":\"toast\",\"param1\":\"12345\",\"param2\":\"67890\"}");
 
    ((XmlElement)tToastNode).SetAttribute("launch",
                string.Format("key1={0}&key2={1}", "12345", 67890));
   
    //將ToastXML轉換成一個ToastNotification物件
    ToastNotification tToastNo = new ToastNotification(tXml);
    //藉由ToastNotificationManager建立Notifier將ToastNotification進行發送
    ToastNotifier tTastNotifier = ToastNotificationManager.CreateToastNotifier();
    tTastNotifier.Show(tToastNo);
}

注意到代碼中有幾個元素:ToastNotification、ToastNotificationManager、ToastNotifier與ToastNotificationHistory;

它們負責Toast Notification能運作的功能與相關的管理。往下將一一說明。

 

 

A. ToastTemplateType

     列舉化所有可用的Toast Template。其種類非常之多,不過WP8.1僅有:ToastText02

     BR208660_ToastText02Phone(en-us,WIN_10)

    

 

B. ToastNotification

    一個Toast notification物件,保存了呈現的樣式、相關的資訊(audio, metadata, expiration time)與事件。發送Toast的單位。

 

B-1. 事件

事件 說明
Activated 發生於用戶點擊了Toast Notification所觸發。可註冊此事件,從中得到ToastNotification物件。
Dismissed 發生於當Toast Notification離線畫面時,不管是用戶明確駁回(由右往左滑開)或是到期。搭配ToastDismissedEventArgs參數可得知其理由。

ToastDismissalReason具有以下三種:UserCanceled、ApplicationHidden、TimedOut。
Failed 當Windows嘗試發出一個Toast Notification所引發的錯誤。搭配ToastFailedEventArgs參數取得錯誤訊息與代號。

 

B-2. 屬性

屬性 Access-Type 描述
Content Read-only Gets the XML that defines the current toast notification.
建構子時給定後就不能再調整。
ExpirationTime Read/write 設定/取得Toast Notification應該多久時間之後消失。
Tag Read/write 選擇性的字串屬性,用來識別Toast Notification在Group中的唯一識別值(uniquely identifies)。
Group Read/write 選擇性的字串屬性,用來組織Toast Notification為同一個群組。
SuppressPopup Read/write 決定Toast Notification是否要Pop-up呈現訊息。

 

 

C. ScheduledToastNotification

     上述ToastNotification是一般的Toast,如果需要具有指定時間才顯示的Toast則需要利用ScheduledToastNotification。

 

C-1. 方法

建構子 說明
ScheduledToastNotification(XmlDocument, DateTime) 初始化一個ScheduledToastNotification實例,它將會被顯示一次

‧content:
    The XML that defines the toast notification content.
‧deliveryTime:
    The date and time that Windows should display the toast notification。

搭配AddToSchedule來指定該ScheduledToastNotification進排程。
ScheduledToastNotification(XmlDocument, DateTime, TimeSpan, UInt32) 創建並初始化一個經常性ScheduledToastNotification的新實例。

‧content:
   The XML that defines the toast notification content.
‧deliveryTime:
   The date and time that Windows should first  display the toast
    notification。
‧snoozeInterval:
    The amount of time between occurrences of the notification. To be
    valid, this value must be no less than 60 seconds and no more than 60
    minutes.
‧maximumSnoozeCountd:
    The maximum number of times to display this notification. Valid
     values range from 1 to 5.

如果您希望發出ScheduledToastNotification是在指定時間開始,並開始後指定時間區間內重覆發送Toast的話,

可以搭配第二個建構子來使用。

舉例來說:我希望在3小時後開始發送Toast,並且開始後每1分鐘再發一次Toast持續5次,那麼一共會有幾個Toast呢?

答案是:6個,第一次3小時到了發出第一個,之後每1分鐘一次共5次,所以有6個,如下圖:

03

 

C-2. 屬性

屬性 Access-Type 說明
Content Read-only Gets the XML that defines this scheduled toast notification.
DeliveryTime Read-only Gets the time that this toast notification is scheduled to be displayed.
Id Read/write Gets a developer-specified value used to identify a specific scheduled toast.
MaximumSnoozeCount Read-only Gets the maximum number of times to display this notification.
SnoozeInterval Read-only Gets the amount of time between occurrences of the notification.

 

C-3. 範例:指定10秒後發出Toast Notification

private void SendAfter10sScheduledToastNotification()
{
        ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        //指定目前時間往後10秒,發送Toast notification
        Int16 dueTimeInSecond = 10;
        DateTime dueTime = DateTime.Now.AddSeconds(dueTimeInSecond);
    
        //取得ScheduledToastNotification物件,指定XML與排程時間
        ScheduledToastNotification scheduledToast = new ScheduledToastNotification(toastXml, dueTime);
 
        //指定一個Toast Id用於識別與刪除之用
        scheduledToast.Id = "Future_Toast";
        //加入排程
        ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledToast);
}

 

C-4. 範例:指定每隔1分鐘發送Toast Notification,持續5次

private void SendIntervalScheduledToastNotification()
{
    //指定區間重覆傳送
    Int16 startTimeInHours = 3;
    DateTime startTime = DateTime.Now.AddHours(startTimeInHours);
    //指定從啟始時間,每1分鐘送出Toast,持續5次。
    ScheduledToastNotification recurringToast = new ScheduledToastNotification(
        toastXml, startTime, new TimeSpan(0, 0, 0, 60), 5);
    recurringToast.Id = "Recurring_Toast";
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(recurringToast);
}

 

更詳細的範例可以參考<How to schedule a toast notification (Windows Runtime apps using C#/VB/C++ and XAML)>。

 

 

D. ToastNotifier

     發出Toast Nofiication時需要經由ToastNotifier負責,它負責Toast Notification發送的排程(schedule)與移除Toast Notification。

當ToastNotifier被建立它就直接Bound於該App,負責該App所有的Toast Notification。

 

D-1. 方法

方法 說明
AddToSchedule 增加指定的ScheduledToastNotification至排程中。
GetScheduledToastNotifications 取得目前排程中的所有ScheduledToastNotification物件集合。
Hide 從畫面中移除指定的Toast Notification。
RemoveFromSchedule 取消排程中指定的ScheduledToastNotification。
Show 呈現指定的Toast Notification。

 

D-2. 範例:刪除指定的ScheduledToastNotification

private void DeleteScheduledToastNotification()
{
    //取得所有ScheduledToastNotification
    var tSceduledToasts = 
        ToastNotificationManager.CreateToastNotifier().GetScheduledToastNotifications();
    foreach (ScheduledToastNotification tToast in tSceduledToasts)
    {
        //刪除指定Id的ScheduledToastNotification
        if (tToast.Id == "Future_Toast")
            ToastNotificationManager.CreateToastNotifier().RemoveFromSchedule(tToast);
    }
}

 

 

E. ToastNotificationManager

     負責建立ToastNotifier來發送Toast Notification,並且提供取得系統提供的Toast XML Template content。    

 

E-1. 方法

方法 說明
CreateToastNotifier() Creates and initializes a new instance of the ToastNotification, bound to the calling application, that lets you raise a toast notification to that app.
CreateToastNotifier(String) Creates and initializes a new instance of the ToastNotification, bound to a specified app, usually another app in the same package.
GetTemplateContent Gets the XML content of one of the predefined toast templates so that you can customize it for use in your notification.

 

 

E. ToastNotificationHistory

     已出現在Action Center中的Toast Notification屬於ToastNotificationHistory,該類別負責管理這些Toast Notification,

包括清除全部或移除指定的Toast Notification。然而,操作存在的ToastNotification則是透過TagGroup來加以管理,

當然ToastNotification與ScheuldedToastNotification均有這二個屬性。

 

E-1. 方法

方法 說明
Clear() Removes all notifications sent by this app from action center.
Clear(String) Removes all notifications from action center that were sent by another app inside the same app package.
Remove(String) Removes an individual toast, with the specified tag label, from action center.
Remove(String, String) Removes a toast notification from the action using the notification's tag and group labels.
Remove(String, String, String) Removes an individual toast notification from action center, identified by the combination of tag label, group label and app Id.
RemoveGroup(String) Removes a group of toast notifications, identified by the specified group label, from action center.
RemoveGroup(String, String) Removes a group of toast notifications sent by the another app inside the same app package from action center using the group label.

 

E-2. 範例:移除指定Tag的Toast Notification

private void btnAction3_Click(object sender, RoutedEventArgs e)
{
    ToastNotificationHistory tHistory = ToastNotificationManager.History;
    tHistory.Remove("WindowsPhone");
}

 

以上介紹了操作toast notification的一些重要類別與元素,接下來針對Action Center補充如何來管理裡面的toast notification。

 

〉Action Center

    根據<Quickstart: Managing toast notifications in action center (Windows Phone Store apps using C#/VB/C++ and XAML)>說明,

要操作Action Center用會到以下幾個元素:

‧ToastNotification

‧ScheduledToastNotification

‧ToastNotifier

‧ToastNotificationHistory

 

直接透過範例程式來看:

 

a. 指定發送的Toast Notification具有Tag與Group

private void btnAction1_Click(object sender, RoutedEventArgs e)
{
    string tXML =
         "<toast>"
        + "<visual>"
        + "<binding template=\"ToastImageAndText01\">"
        + "<image id=\"1\" src=\"ms-appx:///Assets/Logo.scale-240.png\" alt=\"image1\"/>"
        + "<text id=\"1\">Action sample1</text>"
        + "<text id=\"2\">Send Toast Data</text>"
        + "</binding>"
        + "</visual>"
        + "</toast>";
    XmlDocument tXDoc = new XmlDocument();
    tXDoc.LoadXml(tXML);
 
    ToastNotification tToastNo = new ToastNotification(tXDoc);
    tToastNo.Tag = "Windows Phone";
    tToastNo.Group = "JumpStart";
    ToastNotifier tTastNotifier = ToastNotificationManager.CreateToastNotifier();
    //抑制弹出
    //tToastNo.SuppressPopup = true;
    tTastNotifier.Show(tToastNo);
}

    透過在建立ToastNotification時就指定好Tag與Group,接下來在ToastNotificationHistory才有辦法進行管理。

 

b. 指定發送的Toast Notification覆蓋已有的Toast Notification:

private void btnAction2_Click(object sender, RoutedEventArgs e)
{
    string tXML =
         "<toast>"
        + "<visual>"
        + "<binding template=\"ToastImageAndText01\">"
        + "<image id=\"1\" src=\"ms-appx:///Assets/Logo.scale-240.png\" alt=\"image1\"/>"
        + "<text id=\"1\">Action sample2</text>"
        + "<text id=\"2\">Replace Toast Data</text>"
        + "</binding>"
        + "</visual>"
        + "</toast>";
    XmlDocument tXDoc = new XmlDocument();
    tXDoc.LoadXml(tXML);
 
    ToastNotification tToastNo = new ToastNotification(tXDoc);
    //利用相同的tag來取代
    tToastNo.Tag = "Windows Phone";
    tToastNo.Group = "JumpStart";
    tToastNo.ExpirationTime = (DateTimeOffset.Now + TimeSpan.FromHours(2));
    ToastNotifier tTastNotifier = ToastNotificationManager.CreateToastNotifier();
    //抑制弹出
    //tToastNo.SuppressPopup = true;
    tTastNotifier.Show(tToastNo);
}

     透過指定相同的Tag與Group就可以讓App所發出的Toast Notification僅會出現一個在Action Center內,而且內容會換成最新的。

 

c. 刪除所有指定Tag與Group的Toast Notification

private void btnAction3_Click(object sender, RoutedEventArgs e)
{
    ToastNotificationHistory tHistory = ToastNotificationManager.History;
    tnh.Remove("WindowsPhone");
    tnh.RemoveGroup("JumpStart");
}

 

[範例程式]

======

以上是分享Toast Notification操作的重要類別與搭配Action Center來管理它們。

希望對大家在撰寫Windows Phone 8.1的應用有所幫助。

 

References

Quickstart: Sending a toast notification (Windows Runtime apps using JavaScript and HTML)

Quickstart: Using the NotificationsExtensions library in your code.

Toast - commands & Alarm toast notifications sample

Quickstart: Managing toast notifications in action center (Windows Phone Store apps using C#/VB/C++ and XAML)

Managing toast notifications in action center(Windows Phone Store apps)

Action Center Quickstart Sample

Push notification service request and response headers

Windows.UI.Notifications

How to schedule a toast notification (Windows Runtime apps using C#/VB/C++ and XAML)

 

Dotblogs 的標籤: