|
原文地址:http://www.jeffblankenburg.com/post/31-Days-of-Windows-Phone-7c-Day-19-Push-Notifications.aspx
本文讨论另一个重要内容:推送通知
如果对于这个主题不是很熟悉,简单把它想做:代替粗暴的让你的程序没几分钟就检查更新,他能够在有新的数据时通知用户。
为什么使用推送通知?
有一个原因,就是节省电池。从服务端检测数据时需要耗费电量,然后你的手机续航能力将会受到影响:不论你的电池有多好,不使用推送通知都会让你的电池使用时间减低。
第二点,通过他能够让用户知道程序发生了什么,及时他实际上不再运行中。你可以通过他在任何时候来提示用户开启程序进行一些操作。
推送通知过程
你已经理解了我告诉你的所有东西,接下来,我将阐述具体是怎么发生的:
1 用户第一次启动程序,程序将会调用微软的通知服务,并且徐璈一个自定义的URI来进行通信。
2 当你的web端服务有事件发生的时候,你将会通过那个URI来传递数据,通过微软的教程,你可以一步接一步的学习。
调用推送通知服务上的URI
感谢微软,这个很简答。我们需要引用Microsoft.Notification类库,但是另外,我们还需要一个推送通知服务的自定义URI.首先,我创建了一个HttpNotificationChannel对象,他将会自动与PNS通信,然后我创建事件来捕捉返回的结果:
HttpNotificationChannel channel;
void GetPushChannel()
{
channel = new HttpNotificationChannel("BLANKENSOFT_" + DateTime.Now.Ticks.ToString());
channel.ChannelUriUpdated += new EventHandler(channel_ChannelUriUpdated);
channel.Open();
}
void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(delegate
{
URIBlock.Text = channel.ChannelUri.ToString();
});
}
自定义得到URI是:
http://sn1.notify.live.net/throttledthirdparty/01.00/AAHsLicyiJgtTaiDbJoSgmFiAgAAAAADAwAAAAQUZm52OjlzOEQ2NDJDRkl5MEVFMEQ
一旦你拥有了这个URI,你将想保存它到你的web服务中。是你的web服务推送手机消息,我们可以通过三种方式展示:标题提示,toast提示以及raw提示。
不同消息针对不同的需要
Raw提示:用户使用时用来实时更新用户界面
Toast提示:不论你的程序在运行还是关闭,都被接收,但是在程序运行时接收将会很烦人,我将会举例。Toast不会更新呢数据,你需要传递一个Raw提醒来让数据更新。
Title提示:如果你的程序被固定到启动屏幕,你可以更新陈旭标题,比如改变背景图片,设置数字等。
发送Toast提示
一旦我们的呆了推送URI,剩下的就是一堆HTTP消息的事需要处理了。如下:
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channel.ChannelUri.ToString());
sendNotificationRequest.Method = "POST";
//Indicate that you'll send toast notifications!
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
if (string.IsNullOrEmpty(txtMessage.Text)) return;
//Create xml envelope
string data = "X-WindowsPhone-Target: toast\r\n\r\n" +
"" +
"" +
"" +
"{0}" +
"" +
"";
//Wrap custom data into envelope
string message = string.Format(data, txtMessage.Text);
byte[] notificationMessage = Encoding.Default.GetBytes(message);
// Set Content Length
sendNotificationRequest.ContentLength = notificationMessage.Length;
//Push data to stream
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
//Get reponse for message sending
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
正如你所看到的,代码可以变得很复杂。我建议你花点时间在微软的教程上,尤其是推送通知这个方面。 |
|