asp.net 关于android 消息推送
来源:互联网 发布:出纳用什么软件 编辑:程序博客网 时间:2024/06/13 14:44
Introduction
In this article I will try to explain how we can integrate a push notification service for Android using ASP.NET and C#. We all know that mobile applications are booming the market trend. Some custom mobile applications use the push notification service to give updates to application users. Here I will explain how we can use Google’s C2DM (Cloud to Device Messaging) push notification service. The figure above shows a typical flow of push notification.
Requirements
- Components — The physical entities that play a role in C2DM.
- Credentials — The IDs and tokens that are used in different stages of C2DM to ensure that all parties have been authenticated, and that the message is going to the correct place.
Life Cycle Flow
Here are the primary processes involved in cloud-to-device messaging:
- Enabling C2DM - An Android application running on a mobile device registers to receive messages.
- Sending a message - A third-party application server sends messages to the device.
- Receiving a message - An Android application receives a message from a C2DM server.
Action Item From Android Application
- First you need to register your application with C2DM services.http://code.google.com/android/c2dm/signup.html
- Integrate C2DM to the Android application and Google will return the RegistrationID. Use this RegistrationID in the ASP.NET application. http://code.google.com/android/c2dm/index.html#writing_apps
Action Item From ASP.NET Application
On the ASP.NET application side, we require the following credentials:
- RegistrationID
- Google User Account
- Message Text
Your code should follow the three simple steps below to send a Push notification.
- Authentication process with Google.
- Server certification validation.
- Submit a message.
Let’s go one by one.
1. Authentication Process
First you need to pass the SenderID (Google user account name) and its password to get the authentication string. Remember, this authentication string will be used when we submit message to the C2DM server.
![](http://www.codeproject.com/images/minus.gif)
/// <summary>/// Check authentication with supplied credential/// </summary>/// <param name="SenderID">Google EmailID</param>/// <param name="Password">Password of EmailID</param>/// <returns></returns>public string CheckAuthentication(string SenderID, string Password){ string Array = ""; string URL = "https://www.google.com/accounts/ClientLogin?"; string fullURL = URL + "Email=" + SenderID.Trim() + "&Passwd=" + Password.Trim() + "&accountType=GOOGLE" + "&source=Company-App-Version" + "&service=ac2dm"; HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(fullURL); try { //-- Post Authentication URL --// HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); StreamReader Reader; int Index = 0; //-- Check Response Status --// if (Response.StatusCode == HttpStatusCode.OK) { Stream Stream = Response.GetResponseStream(); Reader = new StreamReader(Stream); string File = Reader.ReadToEnd(); Reader.Close(); Stream.Close(); Index = File.ToString().IndexOf("Auth=") + 5; int len = File.Length - Index; Array = File.ToString().Substring(Index, len); } } catch (Exception ex) { Array = ex.Message; ex = null; } return Array;}
2. Server Certification
Here we are not going to install any certificates on the development workstation or application server and then verify it in code. But we are doing a little bit of delegation modeling for the validating server certification.
Make sure this delegation method is called before we submit a message to C2DM.
![](http://www.codeproject.com/images/minus.gif)
//-- Delegate Modeling to Validate Server Certificate --//ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors){ return true;};
3. Send Message
Finally we are in the last step to send the push notification on the device. After successfully finishing the above two steps we have to write the below code to finalize the process.
Now we have to use RegistrationID, Message, and AuthenticationToken/String here.
First create a httpWebRequest
object with the URL that is shown in the code. Also we need to pass the following name value pair as a query string along with the URL.
![](http://www.codeproject.com/images/minus.gif)
registration_id<br />collapse_key<br />delay_while_idle<br />data.payload
(In case you can use data.message
as an alternate.)
Read the below code and try to understand the implementation.
![](http://www.codeproject.com/images/minus.gif)
public string SendMessage(string RegistrationID, string Message, string AuthString){ //-- Create C2DM Web Request Object --// HttpWebRequest Request = (HttpWebRequest)WebRequest.Create( "https://android.clients.google.com/c2dm/send"); Request.Method = "POST"; Request.KeepAlive = false; //-- Create Query String --// NameValueCollection postFieldNameValue = new NameValueCollection(); postFieldNameValue.Add("registration_id", RegistrationID); postFieldNameValue.Add("collapse_key", "1"); postFieldNameValue.Add("delay_while_idle", "0"); // postFieldNameValue.Add("data.message", Message); postFieldNameValue.Add("data.payload", Message); string postData = GetPostStringFrom(postFieldNameValue); byte[] byteArray = Encoding.UTF8.GetBytes(postData); Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; Request.ContentLength = byteArray.Length; Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString); //-- Delegate Modeling to Validate Server Certificate --// ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors) { return true; }; //-- Create Stream to Write Byte Array --// Stream dataStream = Request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //-- Post a Message --// WebResponse Response = Request.GetResponse(); HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) { return "Unauthorized - need new token"; } else if (!ResponseCode.Equals(HttpStatusCode.OK)) { return "Response from web service isn't OK"; } StreamReader Reader = new StreamReader(Response.GetResponseStream()); string responseLine = Reader.ReadLine(); Reader.Close(); return responseLine;}
Using the Code Sample
You can browse the attached sample code. I have created it as a library file. You can add AndroidPushNotification.dllto your project reference and use it.
To send a push notification to the Android application is now just two lines of code.
![](http://www.codeproject.com/images/minus.gif)
using PushNotification;namespace TestAndroidPush{ public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {//-- Create Object of PushNotification class --// PushNotification.PushNotification objPush = new PushNotification.PushNotification(); //-- Send Push Message --// blStatus.Text = objPush.Android("5grDMrPboQIz0Fpyojo-_u2", "myapplication@gmail.com", "myapppassword", "Testing DLL"); } } }}
Call the objPush.Android
function with RegistrationID
, SenderID
, Password
, and Message
.
Conclusion
I hope this code will make your life easy to integrate the Android Push Notification with ASP.NET and C#. Again reminding you that you can use this code to run an Android push notification without any server certification.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
- asp.net 关于android 消息推送
- android个推消息推送,asp.net调用接口
- ASP.NET 推送消息 长连接 IHttpAsyncHandler
- android中关于实现小米消息推送
- 关于android 的消息推送问题解决方案
- AngularJS+ASP.NET MVC+SignalR实现消息推送
- AngularJS+ASP.NET MVC+SignalR实现消息推送
- Asp.net SignalR 实现服务端消息推送到Web端
- Asp.net SignalR 指定用户消息推送简单示例
- ASP.NET Web实时消息后台服务器推送技术--GoEasy
- Asp.net SignalR 指定用户消息推送简单示例
- 关于消息推送
- 关于消息推送
- 关于Asp.net页面跳转、传送消息
- .net平台借助第三方推送服务在推送Android消息(极光推送)
- .net平台借助第三方推送服务在推送Android消息(极光推送)
- .net平台借助第三方推送服务在推送Android消息(极光推送)
- Android消息推送,极光推送
- jQuery EasyUI Form
- netstat查看正在监听的端口
- 黑马程序员_学习日记4_数据库
- 哈佛校训
- DropDownList的绑定数据
- asp.net 关于android 消息推送
- 我们需要专职的QA吗?
- android 编译和arm编译器
- 人机交互在线学习系统
- 给JCombox下拉列表做Tip提示信息
- 如何在cmd命令行中查看、修改、删除与添加环境变量
- vss安装,设置以及与vs2005联合项目操作(转)
- 沮丧的时候,给自己加加油!
- 载入UDF后的设置