虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > WindowsPhone/WindowsMobile > Windows Phone 7推送通知服务范例

Windows Phone 7推送通知服务范例
类别:WindowsPhone/WindowsMobile   作者:码皇   来源:互联网   点击:

推送服务端代码:using System;using System Collections Generic;using System ComponentModel;using System Data;using System Drawing;using System Linq;using System Text;using System Windows Fo

推送服务端代码:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace PushNotifications_CloudServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            byte[] msg = null;
            String type = notificationType.Text;

            switch (type)
            {
                case "Raw":
                    msg = Encoding.UTF8.GetBytes(txtSendMsg.Text);
                    break;
                case "Tile":
                    {
                        string tileMessage = "<?xml version="1.0" encoding="utf-8"?>" +
                                                                    "<wp:Notification xmlns:wp="WPNotification">" +
                                                                      "<wp:Tile>" +
                                                                        "<wp:BackgroundImage>/Images/Cloudy.png</wp:BackgroundImage>" +
                                                                        "<wp:Count>28</wp:Count>" +
                                                                        "<wp:Title>AnthemSord</wp:Title>" +
                                                                      "</wp:Tile>" +
                                                                    "</wp:Notification>";
                        msg = Encoding.UTF8.GetBytes(tileMessage);
                    }
                    break;
                case "Toast":
                    {
                        string toastMessage = "<?xml version="1.0" encoding="utf-8"?>" +
                                                                  "<wp:Notification xmlns:wp="WPNotification">" +
                                                                    "<wp:Toast>" +
                                                                      "<wp:Text1>AnthemSord:</wp:Text1>" +
                                                                      "<wp:Text2>" + txtSendMsg.Text + "</wp:Text2>" +
                                                                    "</wp:Toast>" +
                                                                  "</wp:Notification>";
                        msg = Encoding.UTF8.GetBytes(toastMessage);
                    }
                    break;
                default:
                    break;
            }

            SendNotifications(msg, type); 
        }


        private void SendNotifications(byte[] strBytes, String type)
        {
            HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(notificationUriTextBox.Text); //创建请求对象
            sendNotificationRequest.Method = WebRequestMethods.Http.Post;
            sendNotificationRequest.Headers["X-MessageID"] = Guid.NewGuid().ToString();
            sendNotificationRequest.ContentType = "text/xml;charset=utf-8"; 
           
            switch (type)
            {
                case "Raw":
                    {
                        sendNotificationRequest.Headers.Add("X-NotificationClass", "3");
                    }
                    break;
                case "Tile":
                    {
                        sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token"); 
                        sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
                    }
                    break;
                case "Toast":
                    {
                        sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
                        sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
                    }
                    break;
                default:
                    break;
            }

            using (Stream stream = sendNotificationRequest.GetRequestStream())
            {
                stream.Write(strBytes, 0, strBytes.Length);
            }

            HttpWebResponse respones = (HttpWebResponse)sendNotificationRequest.GetResponse();
            string notificationStatus = respones.Headers["X-NotificationStatus"];
            string notificationChannelStatus = respones.Headers["X-SubscriptionStatus"];
            string deviceConnectionStatus = respones.Headers["X-DeviceConnectionStatus"];
            msgLabel.Text = string.Format("通知状态: {0}  ,管道状态:{1}  , 设备状态: {2} ,  ",
                notificationStatus, notificationChannelStatus, deviceConnectionStatus);

        }

    }
}
 

WP7 终端代码:
只需要一个启动按钮一个信息接受显示TextBlock
XAML:
 
<phone:PhoneApplicationPage
    x:Class="PushNotifications.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Demo" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock FontSize="50" x:Name="PageTitle" Text="Push Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="connect" Height="72" HorizontalAlignment="Left" Margin="6,6,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
            <TextBlock Height="227" HorizontalAlignment="Left" Margin="12,115,0,0" Name="msgtextblock" Text="TextBlock" VerticalAlignment="Top" Width="438" FontSize="28" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>
 
 
cs:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Notification;
using System.Diagnostics;
using System.IO;

namespace PushNotifications
{
    public partial class MainPage : PhoneApplicationPage
    {
        private HttpNotificationChannel httpChannel;
        private const string channelName = "Channel1";

        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            httpChannel = HttpNotificationChannel.Find(channelName);
            if (httpChannel != null)
            {
                httpChannel.Close();
                httpChannel.Dispose();
            }

            //create the channel;
            httpChannel = new HttpNotificationChannel(channelName, "NotificationService");

            httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);

            httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ErrorOccurred);

            httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived);

            httpChannel.Open();

        }
        /// <summary>
        /// 收到讯息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void httpChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
        {
            using (var reader = new StreamReader(e.Notification.Body))
            {
                string msg = reader.ReadToEnd();
                Dispatcher.BeginInvoke(() => {
                    msgtextblock.Text = msg;
                });
            }
        }
        /// <summary>
        /// 显示错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void httpChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            Dispatcher.BeginInvoke(() => {
                msgtextblock.Text = e.Message;
            });
        }
        /// <summary>
        /// 获取uri
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            Debug.WriteLine("Channel Uri:{0}", e.ChannelUri);
        }

    }
}





摘自 据说名字长的都是高手
相关热词搜索: Windows Phone