從新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

[源碼下載]


html

從新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo



做者:webabcd


介紹
從新想象 Windows 8 Store Apps 之 通知html5

  • Toast - 通知的應用
  • Tile - 瓷貼的應用
  • Badge - 徽章的應用
  • Badge - 輪詢服務端以更新 Badge 通知



示例
一、演示 toast 的基本應用
Notification/Toast/Demo.xamlweb

<Page
    x:Class="XamlDemo.Notification.Toast.Demo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Notification.Toast"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Margin="120 0 0 0">

        <TextBox Name="lblMsg" Height="100" TextWrapping="Wrap" AcceptsReturn="True" FontSize="14.667" Margin="0 0 10 0" />

        <!--彈出通知(通知顯示的時間較短)-->
        <Button Name="btnShortToast" Content="Short Toast" Click="btnShortToast_Click_1" Margin="0 10 0 0" />

        <!--彈出通知(通知顯示的時間較長)-->
        <Button Name="btnLongToast" Content="Long Toast" Click="btnLongToast_Click_1" Margin="0 10 0 0" />

        <TextBlock Name="lblStatus" FontSize="14.667" Margin="0 10 0 0" />

    </StackPanel>
</Page>

Notification/Toast/Demo.xaml.csexpress

/*
 * Toast - 通知
 * 
 * ToastNotification - Toast 通知
 *     Content - Toast 的內容,XmlDocument 類型的數據,只讀,其須要在構造函數中指定
 *     ExpirationTime - Toast 通知的過時時間,即若是系統在此屬性指定的時間到了以後尚未顯示對應的 Toast 通知,那麼以後也不要再顯示了
 *     Activated - 用戶點擊通知時觸發的事件
 *     Dismissed - 通知消失時觸發的事件(事件參數 ToastDismissedEventArgs)
 *     Failed - 通知顯示失敗時觸發的事件
 *     
 * ToastDismissedEventArgs - Toast 消失時的事件參數
 *     Reason - 通知消失的緣由(Windows.UI.Notifications.ToastDismissalReason 枚舉)
 *         UserCanceled - 用戶關閉通知
 *         ApplicationHidden - 經過 ToastNotifier.Hide() 關閉通知
 *         TimedOut - 自動關閉通知(短通知 7 秒,長通知 25 秒)
 *         
 * ToastNotificationManager - Toast 通知管理器
 *     CreateToastNotifier() - 建立一個 Toast 通知器,返回 ToastNotifier 類型的數據
 *     CreateToastNotifier(string applicationId) - 爲指定的 app 建立一個 Toast 通知器(這裏指定的是同一 package 內的其餘 app 。注:一個 package 中能夠有多個 app,可是目前沒法經過商店審覈)
 *     
 * ToastNotifier - Toast 通知器
 *     Show() - 顯示指定的 ToastNotification
 *     Hide() - 隱藏指定的 ToastNotification
 *     Setting - 獲取通知設置(Windows.UI.Notifications.NotificationSetting 枚舉)
 *         Enabled - 通知可被顯示
 *         DisabledForApplication - 用戶禁用了此應用程序的通知
 *         DisabledForUser - 用戶禁用了此計算機此帳戶的全部通知
 *         DisabledByGroupPolicy - 管理員經過組策略禁止了此計算機上的全部通知
 *         DisabledByManifest - 應用程序未在 Package.appxmanifest 中啓用 Toast 通知(對應「應用程序 UI」中的小徽標)
 *         
 * 
 * 注:
 * 目前系統支持 8 套 Toast 模板:詳見:ToastWithText.xaml 和 ToastWithImageText.xaml
 * Toast 通知右下角的應用程序徽標,採用的是 Package.appxmanifest 中配置的小徽標,即 30*30 像素的徽標
 * 不能在模擬器中運行
 */

using NotificationsExtensions.ToastContent;
using System;
using Windows.Data.Xml.Dom;
using Windows.UI.Core;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace XamlDemo.Notification.Toast
{
    public sealed partial class Demo : Page
    {
        public Demo()
        {
            this.InitializeComponent();
        }

        // 彈出短時通知
        private void btnShortToast_Click_1(object sender, RoutedEventArgs e)
        {
            // 用一個開源的 Toast 構造器來建立 ToastNotification,具體實現參見:NotificationsExtensions/ToastContent.cs
            IToastText01 templateContent = ToastContentFactory.CreateToastText01();
            templateContent.TextBodyWrap.Text = "我是通知正文,可換行,最多三行。我是通知正文,可換行,最多三行。我是通知正文,可換行,最多三行。";
            templateContent.Duration = ToastDuration.Short; // 短時通知,默認值
            // 當後臺彈出 toast 時,用戶點擊了 toast 後,能夠經過 OnLaunched() 中的 args.Arguments 來獲取此處 Launch 指定的值
            templateContent.Launch = "param";
            IToastNotificationContent toastContent = templateContent; ToastNotification toast = toastContent.CreateNotification(); // 監聽 ToastNotification 的相關事件
            toast.Activated += toast_Activated; toast.Failed += toast_Failed; toast.Dismissed += toast_Dismissed; // 彈出指定的通知
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier(); toastNotifier.Show(toast); lblStatus.Text += "NotificationSetting: " + toastNotifier.Setting.ToString(); lblStatus.Text += Environment.NewLine; // 顯示此 toast 的 xml
            lblMsg.Text = toastContent.GetContent(); } // 彈出長時通知
        private void btnLongToast_Click_1(object sender, RoutedEventArgs e) { // 手工構造 Toast 通知的 xml
            var toastXmlString = "<toast duration='long'>"
                               + "<visual version='1'>"
                               + "<binding template='ToastText01'>"
                               + "<text id='1'>我是通知正文,可換行,最多三行。我是通知正文,可換行,最多三行。我是通知正文,可換行,最多三行。</text>"
                               + "</binding>"
                               + "</visual>"
                               + "<audio silent='true'/>"
                               + "</toast>"; // 將字符串轉換爲 XmlDocument
            XmlDocument toastDOM = new XmlDocument(); toastDOM.LoadXml(toastXmlString); // 實例化 ToastNotification
            ToastNotification toast = new ToastNotification(toastDOM); // 監聽 ToastNotification 的相關事件
            toast.Activated += toast_Activated; toast.Failed += toast_Failed; toast.Dismissed += toast_Dismissed; // 彈出指定的通知
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier(); toastNotifier.Show(toast); lblStatus.Text += "NotificationSetting: " + toastNotifier.Setting.ToString(); lblStatus.Text += Environment.NewLine; // 顯示此 toast 的 xml
            lblMsg.Text = toastXmlString; } async void toast_Dismissed(ToastNotification sender, ToastDismissedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lblStatus.Text += "Toast.Dismissed: " + args.Reason.ToString(); lblStatus.Text += Environment.NewLine; }); } async void toast_Failed(ToastNotification sender, ToastFailedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lblStatus.Text += "Toast.Failed: " + args.ErrorCode.ToString(); lblStatus.Text += Environment.NewLine; }); } async void toast_Activated(ToastNotification sender, object args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lblStatus.Text += "Toast.Activated: " + sender.Content.GetXml(); lblStatus.Text += Environment.NewLine; }); } } }


二、演示 tile 的基本應用
Notification/Tile/Demo.xamlwindows

<Page
    x:Class="XamlDemo.Notification.Tile.Demo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Notification.Tile"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBox Name="lblMsg" Height="100" TextWrapping="Wrap" AcceptsReturn="True" FontSize="14.667" Margin="0 0 10 0" />

            <Button Name="btnXmlTile" Content="經過手工方式構造 xml 模板,以更新 Tile" Click="btnXmlTile_Click_1" Margin="0 10 0 0" />
            
            <Button Name="btnTemplateTile" Content="經過模板幫助類更新 Tile" Click="btnTemplateTile_Click_1" Margin="0 10 0 0" />

            <Button Name="btnClearTile" Content="清除 Tile" Click="btnClearTile_Click_1" Margin="0 10 0 0" />

            <TextBlock Name="lblStatus" FontSize="14.667" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

Notification/Tile/Demo.xaml.csapp

/*
 * Tile - 瓷貼
 * 
 * TileNotification - Tile 通知
 *     Content - Tile 的內容,XmlDocument 類型的數據,只讀,其須要在構造函數中指定
 *     ExpirationTime - Tile 通知的過時時間,即若是系統在此屬性指定的時間到了以後尚未更新對應的 Tile 通知,那麼以後也不要再更新了
 *     
 * TileUpdateManager - Tile 更新管理器
 *     CreateTileUpdaterForApplication() - 建立一個 Tile 更新器,返回 TileUpdater 類型的數據
 *     CreateTileUpdaterForApplication(string applicationId) - 爲指定的 app 建立一個 Tile 更新器(這裏指定的是同一 package 內的其餘 app 。注:一個 package 中能夠有多個 app,可是目前沒法經過商店審覈)
 *     XmlDocument GetTemplateContent(TileTemplateType type) - 獲取系統支持的 Tile 模板,目前共有 46 種,詳見:AllTemplates.xaml
 *     
 * TileUpdater - Tile 更新器
 *     Update() - 更新指定的 TileNotification
 *     Clear() - 清除 TileNotification,開始屏幕的 Tile 將顯示 Package.appxmanifest 中配置的圖片
 *     Setting - 獲取通知設置(Windows.UI.Notifications.NotificationSetting 枚舉)
 *         Enabled - 通知可被顯示
 *         DisabledForApplication - 用戶禁用了此應用程序的通知
 *         DisabledForUser - 用戶禁用了此計算機此帳戶的全部通知
 *         DisabledByGroupPolicy - 管理員經過組策略禁止了此計算機上的全部通知
 *         DisabledByManifest - 應用程序未在 Package.appxmanifest 中啓用 Tile 通知(對應「應用程序 UI」中的徽標和寬徽標)
 *         
 * 注:
 * TileNotification 中引用的圖片能夠來自程序包內,能夠來自 Application Data(僅支持對 local 中圖片文件的引用),能夠來自一個 http 的遠程地址
 * 即 ms-appx:/// 或 ms-appdata:///local/ 或 http:// 或 https://
 * 圖片不能大於 1024*1024 像素,不能大於 200KB
 * 不能在模擬器中運行
 */

using NotificationsExtensions.TileContent;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Notification.Tile
{
    public sealed partial class Demo : Page
    {
        public Demo()
        {
            this.InitializeComponent();
        }

        // 經過手工方式構造 xml 模板,以更新 Tile
        private void btnXmlTile_Click_1(object sender, RoutedEventArgs e)
        {
            // 手工構造 Tile 通知的 xml
            string tileXmlString = "<tile>"
                                 + "<visual>"
                                 + "<binding template='TileWideText03'>"
                                 + "<text id='1'>hi webabcd</text>"
                                 + "</binding>"
                                 + "<binding template='TileSquareText04'>"
                                 + "<text id='1'>hi webabcd</text>"
                                 + "</binding>"
                                 + "</visual>"
                                 + "</tile>";

            // 將字符串轉換爲 XmlDocument
            XmlDocument tileDOM = new Windows.Data.Xml.Dom.XmlDocument();
            tileDOM.LoadXml(tileXmlString);

            // 實例化 TileNotification
            TileNotification tile = new TileNotification(tileDOM);

            // 更新指定的 TileNotification
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.Update(tile);

            // 顯示此 tile 的 xml
            lblMsg.Text = tileDOM.GetXml();

            lblStatus.Text = "NotificationSetting: " + tileUpdater.Setting.ToString();
        }

        // 經過模板幫助類更新 Tile
        private void btnTemplateTile_Click_1(object sender, RoutedEventArgs e)
        {
            // 用一個開源的 Tile 構造器來建立 TileNotification,具體實現參見:NotificationsExtensions/TileContent.cs

            // 構造小 tile 數據
            ITileSquareImage squareContent = TileContentFactory.CreateTileSquareImage();
            squareContent.Image.Src = "http://pic.cnblogs.com/avatar/a14540.jpg?id=24173245";
            squareContent.Image.Alt = "altText";

            // 構造 tile 數據(包括大 tile 數據和小 tile 數據)
            ITileWideImageAndText01 tileContent = TileContentFactory.CreateTileWideImageAndText01();
            tileContent.TextCaptionWrap.Text = "hi webabcd";
            tileContent.Image.Src = "http://pic.cnblogs.com/avatar/a14540.jpg?id=24173245";
            tileContent.Image.Alt = "altText";
            tileContent.SquareContent = squareContent;

            // 建立 TileNotification
            TileNotification tile = tileContent.CreateNotification();

            // 更新指定的 TileNotification
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.Update(tile);

            // 顯示此 tile 的 xml
            lblMsg.Text = tileContent.GetContent();
        }

        // 清除 Tile
        private void btnClearTile_Click_1(object sender, RoutedEventArgs e)
        {
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.Clear();
        }
    }
}


三、演示 badge 的基本應用
Notification/Badge/Demo.xamlasp.net

<Page
    x:Class="XamlDemo.Notification.Badge.Demo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Notification.Badge"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBox Name="lblMsg" Height="100" TextWrapping="Wrap" AcceptsReturn="True" FontSize="14.667" Margin="0 0 10 0" />

            <Button Name="btnUpdateBadgeWidthNumber" Content="以數字的方式更新 Badge" Click="btnUpdateBadgeWidthNumber_Click_1" Margin="0 10 0 0" />

            <Button Name="btnUpdateBadgeWidthIcon" Content="以圖標的方式更新 Badge" Click="btnUpdateBadgeWidthIcon_Click_1" Margin="0 10 0 0" />
            
        </StackPanel>
    </Grid>
</Page>

Notification/Badge/Demo.xaml.csasync

/*
 * Badge - 徽章
 * 
 * BadgeNotification - Badge 通知
 *     Content - Badge 的內容,XmlDocument 類型的數據,只讀,其須要在構造函數中指定
 *     
 * BadgeUpdateManager - Badge 更新管理器
 *     CreateBadgeUpdaterForApplication() - 建立一個 Badge 更新器,返回 BadgeUpdater 類型的數據
 *     CreateBadgeUpdaterForSecondaryTile(string tileId) - 爲指定的 SecondaryTile 建立一個 Badge 更新器,返回 BadgeUpdater 類型的數據
 *     CreateBadgeUpdaterForApplication(string applicationId) - 爲指定的 app 建立一個 Badge 更新器(這裏指定的是同一 package 內的其餘 app 。注:一個 package 中能夠有多個 app,可是目前沒法經過商店審覈)
 *     XmlDocument GetTemplateContent(BadgeTemplateType type) - 獲取系統支持的 Badge 模板(BadgeGlyph 和 BadgeNumber)
 *     
 * BadgeUpdater - Badge 更新器
 *     Update() - 更新指定的 BadgeNotification
 *     Clear() - 清除 BadgeNotification
 */

using NotificationsExtensions.BadgeContent;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Notification.Badge
{
    public sealed partial class Demo : Page
    {
        public Demo()
        {
            this.InitializeComponent();
        }

        // 以數字的方式更新 Badge
        private void btnUpdateBadgeWidthNumber_Click_1(object sender, RoutedEventArgs e)
        {
            // 用一個開源的 Badge 構造器來建立 BadgeNotification,具體實現參見:NotificationsExtensions/BadgeContent.cs

            // 數字在 1 - 99 之間(若是大於 99 則會顯示 99+ ,若是是 0 則會移除 Badge)
            BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent(107);

            // 建立 BadgeNotification
            BadgeNotification badge = badgeContent.CreateNotification();

            // 更新指定的 BadgeNotification
            BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
            badgeUpdater.Update(badge);

            // 顯示此 Badge 的 xml
            lblMsg.Text = badgeContent.GetContent();
        }
        
        // 以圖標的方式更新 Badge
        private void btnUpdateBadgeWidthIcon_Click_1(object sender, RoutedEventArgs e)
        {
            // 用一個開源的 Badge 構造器來建立 BadgeNotification,具體實現參見:NotificationsExtensions/BadgeContent.cs

            // 圖標類型共有 12 種,分別是:None, Activity, Alert, Available, Away, Busy, NewMessage, Paused, Playing, Unavailable, Error, Attention
            BadgeGlyphNotificationContent badgeContent = new BadgeGlyphNotificationContent(GlyphValue.NewMessage);

            // 建立 BadgeNotification
            BadgeNotification badge = badgeContent.CreateNotification();

            // 更新指定的 BadgeNotification
            BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
            badgeUpdater.Update(badge);

            // 顯示此 Badge 的 xml
            lblMsg.Text = badgeContent.GetContent();
        }
    }
}


四、演示如何輪詢服務端以更新 Badge 通知
Notification/Badge/ScheduledBadge.xamlide

<Page
    x:Class="XamlDemo.Notification.Badge.ScheduledBadge"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Notification.Badge"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <Button Name="btnStartPeriodicUpdate" Content="啓動一個「輪詢服務端,然後更新 Badge」的任務" Click="btnStartPeriodicUpdate_Click_1" />

        </StackPanel>
    </Grid>
</Page>

Notification/Badge/ScheduledBadge.xaml.cs函數

/*
 * 演示如何定時更新 Badge 通知
 * 
 * BadgeUpdater - Badge 更新器
 *     StartPeriodicUpdate(Uri badgeContent, DateTimeOffset startTime, PeriodicUpdateRecurrence requestedInterval) - 啓動一個「輪詢服務端,然後更新 Badge」的任務
 *         badgeContent - Badge 通知的內容(xml 格式數據)的 uri 地址
 *         startTime - 能夠指定啓動此任務的時間
 *         requestedInterval - 輪詢服務端的週期(Windows.UI.Notifications.PeriodicUpdateRecurrence 枚舉)
 *             HalfHour, Hour, SixHours, TwelveHours, Daily
 *     StopPeriodicUpdate() - 中止「輪詢服務端,然後更新 Badge」的任務
 */

using System;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace XamlDemo.Notification.Badge
{
    public sealed partial class ScheduledBadge : Page
    {
        public ScheduledBadge()
        {
            this.InitializeComponent();
        }

        // 啓動一個「輪詢服務端,然後更新 Badge」的任務
        private void btnStartPeriodicUpdate_Click_1(object sender, RoutedEventArgs e)
        {
            // 啓動一個循環更新 Badge 的任務,並指定 Badge 內容的數據源和輪詢週期
            BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
            badgeUpdater.StartPeriodicUpdate(new Uri("http://localhost:39629/BadgeContent.xml", UriKind.Absolute), PeriodicUpdateRecurrence.HalfHour);

            // Badge 內容的數據源示例參見 WebServer 項目的 BadgeContent.xml 文件
            // 此處僅用於演示,實際項目中此 Badge 內容一般是變化的
        }
    }
}

WebServer/BadgeContent.xml

<badge version='1' value='17'/>



OK
[源碼下載]

相關文章
相關標籤/搜索