[深入浅出WP8.1(Runtime)]Toast通知

9.1 Toast通知

    Toast通知是在屏幕最顶上弹出来的临时通知,是Windows Phone通用的弹出式短暂的通知,默认的系统消息都是采用Toast通知的形式,比如当你手机收到短信的时候,在手机的顶端弹出的消息就是Toast通知,点击该通知你可以直接进入短信的详情页面,通知显示的时间是7秒钟,7秒钟后会自动消失,如果你想快速关闭通知,可以采用在Toast通知上面向右滑动的手势便可以快速地关闭掉当前的Toast通知。除了系统使用这样的Toast通知之外,第三方的应用程序也是可以使用这种通知的形式,Toast通知不仅仅可以在打开应用程序的时候弹出,也可以在应用程序关闭的情况进行定时通知或者推送通知来进行发送,这也是Toast通知的最大的魅力所在。Toast通知只应该用于用户特别感兴趣的信息,通常涉及某种形式的用户选择。因此,收到IM聊天请求和用户选择接收的信息都是不错的选择。但是,当你考虑使用Toast通知时,你必须认识到非常重要的一点,由于它的短暂性或由于用户设置,用户可能错过而未看到它。Toast通知专为与锁屏提醒、磁贴通知及应用中UI结合使用而设计,旨在让用户即时了解你应用中的相关事件或项目。Toast通知的实现还会分为两种形式,一种是在应用程序本地实现,另外一种是在云端实现,进行推送,那么我们这一小节主要是讲解在应用程序本地实现的Toast通知,在云端实现的Toast通知,可以参考第12章推送通知的内容讲解。

9.1.1 创建一个通知消息

    你的应用要想通过Toast通知通信,必须在应用的清单文件Package.appxmanifest中声明它支持 Toast,否调用Toast通知相关的API将不会生效。在Package.appxmanifest的可视化界面中,找到“Application”->“Notifications”->“Toast capable”,然后设置为“Yes”。打开Package.appxmanifest的代码视图文件,可以看到m3:VisualElements元素的ToastCapable属性设置为true,代码如下所示:

    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="ToastDemo.App">

      <m3:VisualElements …… ToastCapable="true">

        ……

      </m3:VisualElements>

    </Application>

    添加了Toast通知的权限之后,我们来看一段创建Toast通知并弹出的代码示例:

    // 获取Tosat通知的模板

    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

    // 找到模板中“'text'”元素,然后添加通知的内容

    XmlNodeList elements = toastXml.GetElementsByTagName("text");

    elements[0].AppendChild(toastXml.CreateTextNode("A sample toast"));

    // 通过通知的模板创建一个Toast通知

    ToastNotification toast = new ToastNotification(toastXml);

    // 弹出通知

    ToastNotificationManager.CreateToastNotifier().Show(toast);

    下面我们再根据上面的代码来一步步地都讲解Toast通知的编程步骤:

    (1)Toast通知的模板

    每个Toast通知的格式都会对应着一个XML的模板,在我们创建一个Toast通知对象之前,我们首先需要选择Toast通知的模板。Toast通知的模板由ToastTemplateType来进行描述,可以通过Toast通知管理类ToastNotificationManager类的静态方法GetTemplateContent来获取对应的Toast通知模板。在Windows Phone的应用程序里面主要会用到ToastImageAndText01和ToastImageAndText02这两种类型的模板。

    1)ToastText01模板表示是一个最简单的Toast通知模板,只有通知的内容信息,它的XML格式如下所示:

    <toast>

        <visual>

            <binding template="ToastText01">

                <text id="1">bodyText</text>

            </binding> 

        </visual>

    </toast>

    2)ToastText02模板表示是包含消息头和消息体的模板,消息头是一个加粗文本字符串,消息头和消息体会使用空格隔开,它的XML格式如下所示:

    <toast>

        <visual>

            <binding template="ToastText02">

                <text id="1">headlineText</text>

                <text id="2">bodyText</text>

            </binding> 

        </visual>

    </toast>

    (2)添加Toast通知的内容

    获取了Toast通知的模板对象之后,我们可以通过XML对象XmlDocument对象的相关属性和方法来修改XML的内容,从而实现在Toast通知的XML模板上添加消息的内容信息。

    (3)创建Toast通知的对象

    添加好Toast通知的内容之后,我们就可以使用XmlDocument对象来初始化一个Toast通知对象,这时候可以使用ToastNotification类的构造方法ToastNotification(XmlDocument content)方法来进行初始化,这也是Toast通知唯一的构造方法。

    (4)弹出Toast通知

    弹出Toast通知可以使用ToastNotifier类的Show方法,ToastNotifier类是表示Toast通知的通知操作管理器,使用该类可以实现获取Toast列表,打开Toast通知,取下Toast通知等操作。

9.1.2 定期 Toast 通知

    Toast通知不仅仅可以在应用程序运行的时候弹出,还可以在应用程序离开前台的时候弹出,这时候可以使用定期Toast来实现。定期Toast通知就是通过预设未来的一个时间,在这个时间点上弹出Toast通知,如果应用程序这时候不在前台运行,Toast通知也可以运行,用户点击Toast通知的时候可以直接进入当前的应用程序。

    ScheduledToastNotification类表示是定期Toast通知的信息类,你可以使用构造方法ScheduledToastNotification(XmlDocument content, DateTimeOffset deliveryTime)方法来创建一个ScheduledToastNotification对象,然后添加到Toast通知的定时计划里面,其中content参数表示是消息的XML内容,deliveryTime表示是消息弹出的时间。示例代码如下所示:

    // 创建一个ToastText02的消息模板

    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

    // 获取XML模板的text元素

    XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");

    // 设置通知头信息

    toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode("Toast title"));

    // 设置通知体信息

    toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode("Toast content"));

    // 获取一个距离现在还有10秒钟的时间点

    DateTime startTime = DateTime.Now.AddSeconds(10);

    // 使用XML模板和通知的时间创建一个ScheduledToastNotification对象

    ScheduledToastNotification recurringToast = new ScheduledToastNotification(toastXml, startTime);

    // 设置通知的ID

    recurringToast.Id = "ScheduledToast1";

    // 把定时Toast通知添加到通知计划里面

    ToastNotificationManager.CreateToastNotifier().AddToSchedule(recurringToast);

9.1.3 实例演示:Toast通知

下面给Toast通知的示例:实现ToastText01和ToastText02两种模板以及定时通知。

    代码清单9-1:Toast通知(第9章\Examples_9_1)

MainPage.xaml文件主要代码
------------------------------------------------------------------------------------------------------------------
    <StackPanel>
        <Button Content="ToastText01模板通知" x:Name="toastText01" Click="toastText01_Click" Width="370"></Button>
        <Button Content="ToastText02模板通知" x:Name="toastText02" Click="toastText02_Click" Width="370"></Button>
        <Button Content="XML模板通知" x:Name="toastXML" Click="toastXML_Click" Width="370"></Button>
        <Button Content="定时通知" x:Name="scheduledToast" Click="scheduledToast_Click" Width="370"></Button>
        <TextBlock x:Name="info"></TextBlock>
    </StackPanel>
MainPage.xaml.cs文件主要代码
------------------------------------------------------------------------------------------------------------------
    // 弹出ToastText01模板的Toast通知
    private void toastText01_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
        XmlNodeList elements = toastXml.GetElementsByTagName("text");
        elements[0].AppendChild(toastXml.CreateTextNode("Hello Windows Phone 8.1"));
        ToastNotification toast = new ToastNotification(toastXml);
        toast.Activated += toast_Activated;
        toast.Dismissed += toast_Dismissed;
        toast.Failed += toast_Failed;
        ToastNotificationManager.CreateToastNotifier().Show(toast);
    }
    // 弹出ToastText02模板的Toast通知
    private void toastText02_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
        XmlNodeList elements = toastXml.GetElementsByTagName("text");
        elements[0].AppendChild(toastXml.CreateTextNode("WP8.1"));
        elements[1].AppendChild(toastXml.CreateTextNode("Hello Windows Phone 8.1"));
        ToastNotification toast = new ToastNotification(toastXml);
        toast.Activated += toast_Activated;
        toast.Dismissed += toast_Dismissed;
        toast.Failed += toast_Failed;
        ToastNotificationManager.CreateToastNotifier().Show(toast);
    }
   // 直接使用XML字符串来拼接出ToastText02模板的Toast通知
    private void toastXML_Click(object sender, RoutedEventArgs e)
    {
        string toastXmlString = "<toast>"
        + "<visual>"
        + "<binding template='ToastText02'>"
        + "<text id='1'>WP8.1</text>"
        + "<text id='2'>" + "Received: " + DateTime.Now.ToLocalTime() + "</text>"
        + "</binding>"
        + "</visual>"
        + "</toast>";
        XmlDocument toastXml = new XmlDocument();
        toastXml.LoadXml(toastXmlString);
        ToastNotification toast = new ToastNotification(toastXml);
        toast.Activated += toast_Activated;
        toast.Dismissed += toast_Dismissed;
        toast.Failed += toast_Failed;
        ToastNotificationManager.CreateToastNotifier().Show(toast);
    }
    // Toast通知弹出失败的事件
    async void toast_Failed(ToastNotification sender, ToastFailedEventArgs args)
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                info.Text = "Toast通知失败:" + args.ErrorCode.Message;
            });       
    }
    // Toast通知消失的事件,当通知自动消失或者手动取消会触发该事件
    async void toast_Dismissed(ToastNotification sender, ToastDismissedEventArgs args)
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                info.Text = "Toast通知消失:" + args.Reason.ToString();
            });          
    }
    // Toast通知激活的事件,当通知弹出时,点击通知会触发该事件
    async void toast_Activated(ToastNotification sender, object args)
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            info.Text = "Toast通知激活";
        });
    }
    // 定时Toast通知
    private void scheduledToast_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
        XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");
        toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode("Toast title"));
        toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode("Toast content"));
        DateTime startTime = DateTime.Now.AddSeconds(3);
        ScheduledToastNotification recurringToast = new ScheduledToastNotification(toastXml, startTime);
        recurringToast.Id = "ScheduledToast1";
        ToastNotificationManager.CreateToastNotifier().AddToSchedule(recurringToast);
    }

本文来源于《深入浅出Windows Phone 8.1 应用开发》

WP8.1 Runtime文章列表:http://www.cnblogs.com/linzheng/p/3998037.html

源代码下载:http://vdisk.weibo.com/s/zt_pyrfNHb99O

欢迎关注我的微博@WP林政   微信公众号:wp开发(号:wpkaifa)

WP8.1技术交流群:372552293

posted on 2014-09-28 12:40  linzheng  阅读(3980)  评论(2编辑  收藏  举报

导航