全部博文(403)
2012年(403)
分类: 嵌入式
2012-03-11 16:59:27
跟林永坚老师说wp7
概述:
首先为什么使用推送服务?Windows Phone执行模型决定了只有一个第三方的应用可以在前台运行,所以第三方的应用就不能在后台不断的往cloud拉数据,微软提供推送通知服务给第三方应用取得更新通知的消息,服务器主动发起通信,可以减少电池的消耗,
那么推送通知服务的过程和原理是怎样的 呢:
使用规范:
wp7.0版本只支持最多15个推送通知服务,所以最好询问用户是否使用推送通知服务,为用户提供取消订阅的选项
消息类型:
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.ErrorOccurred += new EventHandler
httpchanel.HttpNotificationReceived += new EventHandler
//程序运行时处理toast;
httpchanel.ShellToastNotificationReceived += new EventHandler
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 = "" +
"
"
"
"
" " +
"";
byte[] strbytes = new UTF8Encoding().GetBytes(toastMessage);
SendToastMsg(strbytes);
}
if (type == "TILE")
{
string tileMessage = "" +
"
"
"
"
" " +
"";
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();
}
}
}
} |
效果图: