Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1078979
  • 博文数量: 403
  • 博客积分: 10272
  • 博客等级: 上将
  • 技术积分: 4407
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:22
文章分类

全部博文(403)

文章存档

2012年(403)

分类: 嵌入式

2012-03-11 16:59:27

跟林永坚老师说wp7

概述:

  • 为什么使用推送服务
  • 推送通知服务的原理
  • 使用规范
  • 消息类型(Raw Notification,Toast Notification,tile Notification)
  • 定时更新Tile

首先为什么使用推送服务?Windows Phone执行模型决定了只有一个第三方的应用可以在前台运行,所以第三方的应用就不能在后台不断的往cloud拉数据,微软提供推送通知服务给第三方应用取得更新通知的消息,服务器主动发起通信,可以减少电池的消耗,

那么推送通知服务的过程和原理是怎样的 呢:

  • WP设备到MPNS注册PN服务,并得到唯一的URI,
  • Wp设备吧服务URI传递给Cloud服务,并注册
  • 当有更新消息发生时,Cloud往MPNS发送通知
  • MPNS把消息把更新通知发送到WP设备上

使用规范:

wp7.0版本只支持最多15个推送通知服务,所以最好询问用户是否使用推送通知服务,为用户提供取消订阅的选项

消息类型:

  • Raw Notification:可以发送任何格式的数据,应用程序可以根据需要加工数据,只有在程序运行的时候才接收消息
  • Toast Notification:发送的数据指定为XML,如果程序正在运行,消息发送到应用中,如果程序没有在运行,弹出Toast 消息框显示消息,
  • Tile Notification:发送的数据指定为XML,程序运行时不会接收消息,只有程序被Pin To Start时,更新数据才会发送到Start Screen的 Tile里面,包含三个属性:背景,标题,数目,每个属性都有固定的格式与位置,可以使用其中的属性,不一定三个一起使用,

Xaml.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;
using System.Text;
namespace PushNotifications
{
public partial class MainPage : PhoneApplicationPage
{
HttpNotificationChannel httpchanel;
string channelname = "channel1";
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
httpchanel = HttpNotificationChannel.Find(channelname);
if (httpchanel != null)
{
httpchanel.Close();
httpchanel.Dispose();
}
httpchanel = new HttpNotificationChannel(channelname, "NotificationService");
httpchanel.ChannelUriUpdated += new EventHandler(httpchanel_ChannelUriUpdated);
httpchanel.ErrorOccurred += new EventHandler(httpchanel_ErrorOccurred);
httpchanel.HttpNotificationReceived += new EventHandler(httpchanel_HttpNotificationReceived);
//程序运行时处理toast;
httpchanel.ShellToastNotificationReceived += new EventHandler(httpchanel_ShellToastNotificationReceived);
httpchanel.Open();
//程序不在运行时处理toast;
httpchanel.BindToShellToast();
//程序不在运行时处理toast;
httpchanel.BindToShellTile();
}
void httpchanel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
}
void httpchanel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
using(var Reader=new StreamReader(e.Notification.Body))
{
string msg = Reader.ReadToEnd();
Dispatcher.BeginInvoke(() => {
MessageBox.Show(msg);
});
}
}
void httpchanel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
Dispatcher.BeginInvoke(()=>{
MessageBox.Show(e.Message);
});
}
void httpchanel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Debug.WriteLine("ChannelUri{0}", e.ChannelUri);
}
}
}

  

xaml代码:

x:Class="PushNotifications.MainPage"
xmlns=""
xmlns:x=""
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d=""
xmlns:mc=""
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">

  云端程序处理代码:

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 CloudServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void SendRawMsg(byte[] bytes)
{
HttpWebRequest sendrequest = (HttpWebRequest)WebRequest.Create(textBox1.Text);
sendrequest.Method = WebRequestMethods.Http.Post;
sendrequest.Headers["X-MessageID"] = Guid.NewGuid().ToString();
sendrequest.ContentType = "text/xml;charset=utf-8";
sendrequest.Headers.Add("X-NotificationClass", "3");
sendrequest.ContentLength = bytes.Length;
byte[] notificationmsg = bytes;
using (Stream requeststream = sendrequest.GetRequestStream())
{
requeststream.Write(notificationmsg, 0, notificationmsg.Length);
}
HttpWebResponse response = (HttpWebResponse)sendrequest.GetResponse();
string msgstatus = response.Headers["X-NotificationStatus"];
string channelstatus = response.Headers["X-SubscriptionStatus"];
string devicestatus = response.Headers["X-DeviceConnectionStatus"];
label6.Text = string.Format("消息状态:{0},管道状态:{1},设备连接状态:{2}", msgstatus, channelstatus, devicestatus);
}
private void button1_Click(object sender, EventArgs e)
{
string msg = string.Format("消息类型:{0}{1}{2},{3}度", comboBox1.Text, comboBox2.Text, comboBox3.Text, textBox5.Text);
string type = comboBox1.Text.ToUpper();
MessageBox.Show(type);
if (type == "RAW")
{
byte[] strbytes = new UTF8Encoding().GetBytes(msg);
SendRawMsg(strbytes);
}
if (type == "TOAST")
{
string toastMessage = "" +
"" +
"" +
"天气更新" +
"" + msg + "" +
" " +
"";
byte[] strbytes = new UTF8Encoding().GetBytes(toastMessage);
SendToastMsg(strbytes);
}
if (type == "TILE")
{
string tileMessage = "" +
"" +
"" +
"Red.jpg" +
"" + msg + "" +
" " +
"";
byte[] strbytes = new UTF8Encoding().GetBytes(tileMessage);
SendTileMsg(strbytes);
}
}
private void SendTileMsg(byte[] tile)
{
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 = textBox1.Text;
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast 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["X-MessageID"] = Guid.NewGuid().ToString();
// Set the notification payload to send.
byte[] notificationMessage = tile;
// 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.
label6.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
label6.Text = "Exception caught sending update: " + ex.ToString();
}
}
private void SendToastMsg(byte[] toastmsg)
{
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 = textBox1.Text;
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast 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["X-MessageID"] = Guid.NewGuid().ToString();
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
// Set the web request content length.
sendNotificationRequest.ContentLength = toastmsg.Length;
// Set the notification payload to send.
byte[] notificationMessage = toastmsg;
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.
label6.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
label6.Text = "Exception caught sending update: " + ex.ToString();
}
}
}
}

  效果图:

阅读(733) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~