日期:2014-05-17 浏览次数:20974 次
首先是用java来实现简单的Server端(http的请求内容格式可以参考msdn:http://msdn.microsoft.com/zh-cn/library/hh202945(v=vs.92)):
/**
* 推送toast通知
* @param uriString 推送服务通知uri
* @param title toast标题
* @param content toast内容
* @param param 页面跳转参数
* @return 推送通知服务响应码
* @throws IOException
*/
public static int pushToastNotifications(String uriString, String title, String content, String param) throws IOException{
String toastMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + title + "</wp:Text1>" +
"<wp:Text2>" + content + "</wp:Text2>" +
"<wp:Param>"+ param +"</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
URL url = null;
HttpURLConnection http = null;
try{
url = new URL(uriString);
http = (HttpURLConnection)url.openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
http.setRequestProperty("X-WindowsPhone-Target", "toast");
http.setRequestProperty("X-NotificationClass", "2");
http.setRequestProperty("Content-Length", "1024");
http.getOutputStream().write(toastMsg.getBytes());
// 刷新对象输出流,将任何字节都写入潜在的流中
http.getOutputStream().flush();
// 关闭输出流
http.getOutputStream().close();
}
catch(Exception e) {
e.printStackTrace();
}
finally{
if(http != null){
http.disconnect();
}
}
return http.getResponseCode();
}
服务端的测试数据:
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.in.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 该uri是客户端运行并创建通道之后获得的
String urls = "http://db3.notify.live.net/throttledthirdparty/01.00/AAHGO5Q4sO3ZQa1cBCWwx4X9AgAAAAADAQAAAAQUZm52OjIzOEQ2NDJDRkI5MEVFMEQ";
String text1 = "中文";
String text2 = "English";
String param = "/NotificationPage.xaml?NavigatedFrom = ToastNotification&uri=http://baike.baidu.com/"; // 推送负载中,& 要转换写为&
try {
int code = pushToastNotifications(urls, text1, text2, param);
System.out.println("Response code : "+code);
}
catch (IOException e) {
e.printStackTrace();
}
}这里主要是为了演示当程序不在前台运行时Toast消息到达并点击Toast,来实现跳转到指定页面的效果。在客户端程序中本次demo会实现两个页面:MainPage.xaml和NotificationPage.xaml;MainPage.xaml用于获得通道uri,NotificationPage.xaml用于实现接收Toast时的指定跳转页面。
(1)a. MainPage.xaml
<phone:PhoneApplicationPage
x:Class="PushNotificationDemo.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="800"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"