【转载】如何发送和接收 Windows Phone 的磁贴通知

http://msdn.microsoft.com/zh-cn/library/hh202970(v=vs.92).aspx

2012/2/9

本主题介绍向 Microsoft 推送通知服务发送磁贴通知以便更新 Windows Phone 上应用程序的固定磁贴所需的步骤。Windows Phone 的推送通知概述包含有关磁贴通知以及如何使用这些通知的信息。

可以在 Windows Phone 的代码示例中找到这个已完成的示例。

重要说明重要说明:

本主题中从 Web 服务器上运行的 ASP.NET 网页发送磁贴通知部分需要安装完整版本的 Visual Studio 或免费的 Microsoft Visual Web Developer 2010 Express



在本节中,我们创建一个在 Windows Phone 上运行的应用程序,该应用程序创建一个推送通知通道并处理通知事件。

重要说明重要说明:

为了简单起见,我们将 Toast 通知 URI 复制并粘贴到发送通知的网页。通常,此 URI 传递给已为应用程序创建的 Web 服务。

创建用来接收磁贴通知的推送客户端的步骤

  1. 打开 Visual Studio 并创建一个新的应用程序。模板应该为 Silverlight for Windows Phone C# 类别下的“Windows Phone 应用程序”

  2. 将项目命名为 TileNotificationClient

  3. 向 MainPage.xaml.cs 文件的顶部添加以下 using 指令。

    using Microsoft.Phone.Notification;
    
    
  4. 为用于更新磁贴的图像创建两个或三个图形。例如,您可以使用 Microsoft 绘图创建三个 173 x 173 像素的 .jpg 文件,这三个文件都是纯色的,分别是红色、绿色和蓝色。将它们命名为 Red.jpg、Green.jpg 和 Blue.jpg。

  5. 通过右键单击 TileNotificationSample 项目名称并选择 “添加...”,然后选择“现有项”向项目中添加图形文件。选择您创建的三个图像并将它们添加到项目中。

  6. “解决方案资源管理器”中选择 Red.jpg。在“属性”窗口中,将“生成操作”设置为“内容”以将该图形包含在 .xap 文件中。对其他 .jpg 文件重复这些步骤。

  7. 用下面的代码替换 MainPage 构造函数。该代码查看在应用程序的早期实例中是否已设置磁贴通知通道。如果找到通知通道,则通知通道连接到通知事件。如果未找到通知通道,则创建通知通道,然后将其连接到通知事件。

            public MainPage()
            {
                /// Holds the push channel that is created or found.
                HttpNotificationChannel pushChannel;
    
                // The name of our push channel.
                string channelName = "TileSampleChannel";
    
                InitializeComponent();
    
                // Try to find the push channel.
                pushChannel = HttpNotificationChannel.Find(channelName);
    
                // If the channel was not found, then create a new connection to the push service.
                if (pushChannel == null)
                {
                    pushChannel = new HttpNotificationChannel(channelName);
    
                    // Register for all the events before attempting to open the channel.
                    pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                    pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
    
                    pushChannel.Open();
    
                    // Bind this new channel for Tile events.
                    pushChannel.BindToShellTile();
    
    
                }
                else
                {
                    // The channel was already open, so just register for all the events.
                    pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                    pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
    
                    // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                    System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
                    MessageBox.Show(String.Format("Channel Uri is {0}",
                        pushChannel.ChannelUri.ToString()));
    
                }
            }
    
    
    
  8. 下面,我们添加事件处理程序的代码。第一个事件处理程序用于 ChannelUriUpdated 事件。为了简单起见,在此处显示通道 URI,但通常此 URI 将发送回 Web 服务。

            void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
            {
    
                Dispatcher.BeginInvoke(() =>
                {
                    // Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                    System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
                    MessageBox.Show(String.Format("Channel Uri is {0}",
                        e.ChannelUri.ToString()));
                    
                });
            }
    
    
  9. 下一个事件处理程序用于错误处理。您的代码应该能够正常处理通知错误,因为数据连接可能因手机的位置和服务而异。

            void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
            {
                // Error handling logic for your particular application would be here.
                Dispatcher.BeginInvoke(() =>
                    MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
                        e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
                        );
            }
    
    

推送客户端代码现在已完成。完成用来发送通知的网页之后,我们将运行此代码。

在本节中,我们创建一个 ASP.NET 网页,该网页使用在设备上创建推送通道时返回的 URI 来发送磁贴通知。

若要创建 ASP.NET 项目,您需要完整版本的 Visual Studio 或免费的 Microsoft Visual Web Developer 2010 Express

创建用来发送磁贴通知的 ASP.NET 页面的步骤

  1. 打开 Visual Studio 的另一个实例并创建一个新的应用程序。模板应该为 Web C# 类别下的“ASP.NET Empty Web 应用程序”

  2. 将项目命名为 SendTile

  3. 通过右键单击“SendTile”项目名称,然后依次选择“添加”“新项”“Web 表单”向项目中添加一个新的 Web 表单。

  4. 将该表单命名为“SendTile”,然后单击“添加”按钮。

  5. 通过在“解决方案资源管理器”中右键单击“SendTile.aspx”,然后选择“设为起始页”使 SendTile 表单成为起始页。

  6. 下一步是向 SendTile.aspx Web 表单中添加以下控件。

    控件类型

    控件 ID

    控件的文本

    TextBox

    TextBoxUri

    输入 URI:

    TextBox

    TextBoxTitle

    输入标题:

    TextBox

    TextBoxBackgroundImage

    输入图像:

    TextBox

    TextBoxCount

    输入计数:

    TextBox

    TextBoxBackTitle

    输入背面标题:

    TextBox

    TextBoxBackBackgroundImage

    输入背面背景图像:

    TextBox

    TextBoxBackContent

    输入背面内容:

    Button

    ButtonSendTile

    发送磁贴通知:

    TextBox

    TextBoxResponse

    响应:

    “发送磁贴”按钮将拥有 ButtonSendTile_Click 事件处理程序。将 SendTile.aspx 的内容替换为以下代码以创建这些控件。

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendTile.aspx.cs" Inherits="SendTile.SendTile" %>
    <!-- 
        Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
        Use of this sample source code is subject to the terms of the Microsoft license 
        agreement under which you licensed this sample source code and is provided AS-IS.
        If you did not accept the terms of the license agreement, you are not authorized 
        to use this sample source code.  For the terms of the license, please see the 
        license agreement between you and Microsoft.
    -->
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <body>
        <form id="form1" runat="server">
        <div>
        
            <br />
            Enter URI:</div>
        <asp:TextBox ID="TextBoxUri" runat="server" Width="666px"></asp:TextBox>
        <br />
        <br />
        Enter Front Title:<br />
        <asp:TextBox ID="TextBoxTitle" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Front Background Image:<br />
        <asp:TextBox ID="TextBoxBackgroundImage" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Front Count:<br />
        <asp:TextBox ID="TextBoxCount" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        Enter Back Title:<br />
        <asp:TextBox ID="TextBoxBackTitle" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Back Background Image:<br />
        <asp:TextBox ID="TextBoxBackBackgroundImage" runat="server"></asp:TextBox>
        <br />
        <br />
        Enter Back Content:<br />
        <asp:TextBox ID="TextBoxBackContent" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="ButtonSendTile" runat="server" onclick="ButtonSendTile_Click" 
            Text="Send Tile Notification" />
        <br />
        <br />
        Response:<br />
        <asp:TextBox ID="TextBoxResponse" runat="server" Height="78px" Width="199px"></asp:TextBox>
        </form>
    </body>
    </html>
    
    
  7. 向 SendTile.aspx.cs 文件的顶部添加以下 using 指令。

    using System.Net;
    using System.IO;
    using System.Text;
    
    
  8. 添加 ButtonSendTile_Click 事件处理程序的代码。该代码将获取在第一个 TextBox 中输入的 URI,形成磁贴通知消息,然后将其发布到 Microsoft 推送通知服务。

                 protected void ButtonSendTile_Click(object sender, EventArgs e)
            {
    
    
                try
                {
                    // Get the URI that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
                    // Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
                    // notifications out to.
                    string subscriptionUri = TextBoxUri.Text.ToString();
    
    
                    HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
    
                    // Create an HTTPWebRequest that posts the Tile notification to the Microsoft Push Notification Service.
                    // HTTP POST is the only method allowed to send the notification.
                    sendNotificationRequest.Method = "POST";
    
                    // The optional custom header X-MessageID uniquely identifies a notification message. 
                    // If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
                    // sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
    
                    // Create the Tile message.
                      string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                      "<wp:Notification xmlns:wp=\"WPNotification\">" +
                          "<wp:Tile>" +
                            "<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
                            "<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
                            "<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
                            "<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
                            "<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
                            "<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
                         "</wp:Tile> " +
                      "</wp:Notification>";
     
                    // Set the notification payload to send.
                    byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);
    
                    // Set the web request content length.
                    sendNotificationRequest.ContentLength = notificationMessage.Length;
                    sendNotificationRequest.ContentType = "text/xml";
                    sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
                    sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
    
    
                    using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                    {
                        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
                    }
    
                    // Send the notification and get the response.
                    HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                    string notificationStatus = response.Headers["X-NotificationStatus"];
                    string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                    string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
    
                    // Display the response from the Microsoft Push Notification Service.  
                    // Normally, error handling code would be here. In the real world, because data connections are not always available,
                    // notifications may need to be throttled back if the device cannot be reached.
                    TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
                }
                catch (Exception ex)
                {
                    TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
                }
    
            }
    
    
    

若要运行此示例,我们首先运行推送客户端代码以创建通道并获取 URI。然后,我们在网页中使用此 URI 来发送磁贴。

运行示例的步骤

  1. 回到 TileNotificationClient 项目并运行该项目。Windows Phone 模拟器进行初始化,应用程序随后启动。一段时间之后,应用程序应该显示带有 URI 的消息。此 URI 还显示在 Visual Studio 调试器的“输出”窗口中。

    AP_Push_OutputWindow
    提示提示:

    在 Visual Studio 2010 Express for Windows Phone 中,默认设置是在调试会话期间不显示“输出”窗口。您可以通过转到“调试”菜单,选择“窗口”,然后选择“输出”来显示“输出”窗口。滚动窗口以查找 URI。

  2. 现在,已创建通知通道。将此 URI 从 Visual Studio 调试器“输出”窗口复制到剪贴板。

  3. 在模拟器上运行的 Windows Phone 应用程序中,通过长按应用程序列表中的 TileNotificationClient 名称,然后选择“固定到‘开始’屏幕”将应用程序的磁贴固定到“开始”屏幕。这就是将要更新的磁贴。

  4. 切换到“SendTile”项目并运行该项目。

  5. 在 URI 文本框中,粘贴从上一个项目中复制的 URI。

  6. 为磁贴输入标题、计数和图像。使用 .jpg 文件的全名(如 Red.jpg)作为图像名称。

    AP_Push_SendTile

    请注意,也可以使用 BindToShellTile(Collection<(Of <<'(Uri>)>>)) 方法向远程图像文件发送 URI。

  7. 单击“发送磁贴”按钮。固定到“开始”屏幕的磁贴应该更新。如果您设置磁贴背面的任何属性,则几秒之后磁贴将翻转磁贴以显示其背面。如果您将某个字段保留空白(如“标题”),则不会更新该字段。

    AP_PushTileUpdate

现在,您已经了解如何通过使用 ASP.NET 页面向 Windows Phone 发送通知来更新磁贴。

原文地址:https://www.cnblogs.com/fx2008/p/2471731.html