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

[源码下载]


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



作者:webabcd


介绍
重新想象 Windows 8 Store Apps 之 通知

  • Toast - 通知的应用
  • Tile - 瓷贴的应用
  • Badge - 徽章的应用
  • Badge - 轮询服务端以更新 Badge 通知



示例
1、演示 toast 的基本应用
Notification/Toast/Demo.xaml

<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.cs

/*
 * 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;
            });
        }
    }
}


2、演示 tile 的基本应用
Notification/Tile/Demo.xaml

<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.cs

/*
 * 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();
        }
    }
}


3、演示 badge 的基本应用
Notification/Badge/Demo.xaml

<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.cs

/*
 * 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();
        }
    }
}


4、演示如何轮询服务端以更新 Badge 通知
Notification/Badge/ScheduledBadge.xaml

<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
[源码下载]

posted @ 2013-06-17 10:06  webabcd  阅读(3124)  评论(14编辑  收藏  举报