`
duoerbasilu
  • 浏览: 1541669 次
文章分类
社区版块
存档分类
最新评论

windowsphone7 消息推送Demo

 
阅读更多

首先是用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&amp;uri=http://baike.baidu.com/";  // 推送负载中,& 要转换写为&amp;
		
		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}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent" Height="800" Width="480">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="推送通知服务" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="推送通知" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button x:Name="linkButton" Content="连接" Height="72" HorizontalAlignment="Left" Margin="83,82,0,0" VerticalAlignment="Top" Width="281" Click="linkButton_Click" />
        </Grid>
        
        <TextBlock x:Name="msgTextBlock" Grid.Row="2" Width="450" TextWrapping="Wrap"/>
        
        <Button Grid.Row="3" Click="OnNavigateToWebBrowser" Content="下一个视图" Height="100" Width="300"/>
    </Grid>

</phone:PhoneApplicationPage>
b. MainPage.xaml.cs

using System;
using System.Windows;
using Microsoft.Phone.Controls;
///引用通知服务命名空间
using Microsoft.Phone.Notification;
using System.Diagnostics;
using System.IO;

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

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

        private void linkButton_Click(object sender, RoutedEventArgs e)
        {
            httpChannel = HttpNotificationChannel.Find(channelName);
            if (httpChannel == null)
            {
                httpChannel = new HttpNotificationChannel(channelName, "NotificationServer"); 

                //注册URI
                httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);

                //发生错误的事件
                httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ErrorOccurred);
                //toast 推送通知服务事件
                httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived);

                //打开连接
                httpChannel.Open();
                //绑定toast 推送服务
                httpChannel.BindToShellToast();
            }
            else
            {
                //注册URI
                httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);
                //发生错误的事件
                httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ErrorOccurred);
                //toast 推送通知服务事件
                httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived);

                linkButton.IsEnabled = false;
                msgTextBlock.Text = "connected";
            }
        }

        private void OnNavigateToWebBrowser(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/NotificationPage.xaml", UriKind.Relative));
        }

        void httpChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            string msg = string.Empty;
            foreach (var key in e.Collection.Keys)
            {
                msg += key + " : " + e.Collection[key] + Environment.NewLine;
            }
            Dispatcher.BeginInvoke(() =>
            {
                msgTextBlock.Text = msg;
            });
        }

        void httpChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            //子线程中更新UI
            Dispatcher.BeginInvoke(() =>
            {
                msgTextBlock.Text = e.Message; 
                linkButton.IsEnabled = true;
            });
        }

        void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            Debug.WriteLine("CahnnelUri:{0}", e.ChannelUri);
            Dispatcher.BeginInvoke(() =>
            {
                linkButton.IsEnabled = false;
            });
        }
    }
}
(2)a. NotificationPage.xaml

<phone:PhoneApplicationPage 
    x:Class="PushNotificationDemo.NotificationPage"
    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"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="推送通知" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Background="Transparent">
            <phone:WebBrowser x:Name="Browser" IsScriptEnabled="True" ScriptNotify="OnScriptNotify"/>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

b. NotificationPage.xaml.cs

using System;
using Microsoft.Phone.Controls;

namespace PushNotificationDemo
{
    public partial class NotificationPage : PhoneApplicationPage
    {
        #region Constants

        private const string DefaultUrl = "http://www.baidu.com/";
        private string m_UriString = string.Empty;

        #endregion

        public NotificationPage()
        {
            InitializeComponent();

            Browser.Navigate(new Uri(DefaultUrl));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                m_UriString = NavigationContext.QueryString["uri"];
                Browser.Navigate(new Uri(m_UriString));
            }
            catch
            {
            }
        }

        private void OnScriptNotify(object sedner, NotifyEventArgs args)
        {
        }
    }
}


最后就是实验证明了。运行的效果图如下:


点击跳转后效果图:




分享到:
评论

相关推荐

    c#友盟推送Demo(包括安卓和IOS) U-Push

    通过这个C#友盟推送Demo,你可以快速掌握如何在你的项目中集成友盟U-Push服务。它不仅展示了基本的推送功能,还可能涵盖了错误处理、调试技巧等内容,有助于你在实际开发中灵活运用。同时,由于C#语言的广泛适用性,...

    windows phone 7 各种demo

    10. **推送通知**:通过Microsoft的Push Notification Service (MPNS),开发者可以实现远程通知,即使应用不在后台运行也能接收到消息。 11. **性能优化**:Windows Phone 7设备的硬件配置有限,因此性能优化是开发...

    WP7推送通知DEMO

    在Windows Phone 7 (WP7)平台上,推送通知(Push Notifications)是开发者向用户设备发送实时信息的一种机制,它使得应用程序即使在后台运行或者完全关闭的状态下也能接收到来自服务器的数据更新。本DEMO旨在展示...

    微软消息推送

    总的来说,这个“微软消息推送”的小demo是一个很好的学习资源,帮助开发者快速理解和实践Windows Phone应用的推送通知功能。通过分析和运行这个示例,可以深入掌握MPNS的工作原理,为自己的应用添加类似功能。

    WindowsPhone培训手册

    [培训]WP_第5章_数据存储 网络 推送_Demo.rar [培训]WP_第6章_传感器 位置服务_Demo.rar [培训]WP_第7章_多媒体_Demo.rar [培训]WP_第8章_依赖属性 数据绑定_Demo.rar [培训]WP_第9章_变换 动画 模板_Demo.rar .... ...

    Windows Phone For PushNotification Demo

    Windows Phone PushNotification示例,示例分为两个工程,一个客户端(放手机里的),一个发送端(WinForm程序),首页要启动WP7客户端,取得uri。因为uri要从Microsoft Push Notifications Service服务器获得,保持您...

    [培训]WP_第5章_数据存储 网络 推送_Demo

    【WP_第5章_数据存储 网络 推送_Demo】是Windows Phone技术培训资料中的一个重要章节,主要涵盖了在Windows Phone平台上进行数据存储、网络通信以及推送通知的相关技术。这一章节通过一系列的Demo实例,帮助开发者...

    windows phone开发介绍

    ### Windows Phone 开发介绍 ...同时,掌握Windows Phone应用的开发流程、UI设计原则以及推送通知等功能也是必不可少的。此外,与云服务的集成也为Windows Phone应用提供了更多的可能性和发展空间。

    Yii1.1框架实现PHP极光推送消息通知功能

    Yii1.1框架是基于PHP语言开发的一个高级、模块化的Web应用开发框架,而极光推送是一个跨平台的推送消息服务,它支持Android、iOS和Windows Phone等多种操作系统。本文将详细介绍如何在Yii1.1框架下实现通过极光推送...

    NEICWindowsPhone技术培训资料专题

    教程名称: NEIC Windows Phone技术培训资料专题【】[培训]WP_第1章_Windows Phone平台预览_Demo【】[培训]WP_第2章_UI控件_Demo【】[培训]WP_第3章_程序的基本概念和架构_Demo【】[培训]WP_第4章_特性_Demo【】...

    ionic的15个demo和一个真实项目

    5. **demo10**:推送通知,展示了集成推送通知服务的实现,让应用可以接收远程消息。 6. **ionic-cnodejs-master**:可能是一个完整的社区应用示例,使用了 CNode.js 社区的数据,展示了如何结合 API 进行数据交换...

    移动开发经典Demo

    6. **推送通知**:集成Google Firebase Cloud Messaging(FCM)或Apple Push Notification Service(APNS)进行实时消息推送。 7. **动画和过渡效果**:如何实现平滑的动画效果,比如Android的Property Animation和...

    ionic.wp8.plugin.demo:这是离子wp8的插件演示(Windows Phone)

    ionic.wp8.plugin.demo 这是离子wp8的插件演示(Windows Phone) 推送通知(以本机方式) 地理位置(console.log纬度+经度坐标) 相机 动作栏 对话 键盘 状态栏(不确定它是否起作用) 剪贴板

    phonegap demo

    4. **插件系统**:PhoneGap的插件机制允许开发者扩展其功能,以访问更深入的设备特性,如推送通知、蓝牙通信等。 5. **Cordova核心**:PhoneGap基于Apache Cordova,后者是PhoneGap的开源基础。Cordova提供了与设备...

    ASP.NET SignalR编程实战(附书中完整Demo示例源码)(0520_).rar

    ASP.NET SignalR是一种实时通信库,它允许开发者创建实时、双向通信的应用程序,使得服务器能够实时推送信息到客户端,而不仅仅是传统的请求-响应模式。在ASP.NET框架中,SignalR提供了一种简单的方式来处理长轮询、...

    WP 微信SDK示例

    微信服务器会向应用推送消息,如支付结果通知。开发者需要设置消息处理函数,监听并处理这些通知,更新应用状态。 8. **Demo程序** 提供的"Demo程序"包含了上述功能的实例代码,开发者可以通过分析和运行这个示例...

    azure-mobile-engagement-app-windows:包含Azure Mobile Engagement Windows App的源代码-windows source code

    创建针对特定细分市场的营销活动/推送通知 使用丰富HTML发送个性化的应用程序外通知,民意调查和应用程序内通知 使用开放平台API集成和自动化CRM / CMS / IT系统 查找适用于所有主要平台的SDK:iOS,Android,...

    Kido_Xamarin_SampleDemo:这是一个示例空白项目,用作连接 Kidozen 平台和 Xamarin 的基础项目

    4. **推送通知**:Kidozen 支持跨平台的推送通知服务,使开发者能够轻松向用户的设备发送消息。 ### 示例项目结构 在 `Kido_Xamarin_SampleDemo-master` 压缩包中,通常会包含以下关键文件和目录: - **Solution ...

    待办事情软件,记事本

    3. **提醒功能**:具备定时提醒功能,通过推送通知确保用户不会忘记重要的事项。 4. **日历集成**:与iOS内置的日历应用集成,用户可以直接在日历视图中查看和管理任务。 5. **跨设备同步**:支持Apple的iCloud...

    PhoneGap简单示例

    它们可以连接到PhoneGap Build服务,自动编译并推送应用到各个目标平台。 6. 跨平台开发:PhoneGap的跨平台特性意味着开发者只需要编写一次代码,就可以在多个操作系统上运行。但需要注意的是,虽然大部分功能是跨...

Global site tag (gtag.js) - Google Analytics