65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET 和 C# 实现 Android 推送通知

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (35投票s)

2012 年 3 月 2 日

CPOL

4分钟阅读

viewsIcon

256919

downloadIcon

10561

只需三个步骤即可实现 Android 推送通知,操作简单方便。

引言

在本文中,我将尝试解释如何使用 ASP.NET 和 C# 为 Android 集成推送通知服务。我们都知道移动应用程序正在蓬勃发展。一些自定义移动应用程序使用推送通知服务向应用程序用户提供更新。在这里,我将解释如何使用 Google 的 C2DM(Cloud to Device Messaging)推送通知服务。上图显示了推送通知的典型流程。

要求

  • 组件 — 在 C2DM 中起作用的物理实体。
  • 凭据 — 在 C2DM 的不同阶段使用的 ID 和令牌,以确保所有各方都已通过身份验证,并且消息已发送到正确的位置。
Components
移动设备 运行使用 C2DM 的 Android 应用程序的设备。这必须是安装了 Market 的 Android 2.2 设备,并且必须至少有一个已登录的 Google 帐户。
第三方应用程序服务器 开发人员在应用程序中实现 C2DM 时设置的应用程序服务器。第三方应用程序服务器通过 C2DM 服务器将数据发送到设备上的 Android 应用程序。
C2DM 服务器 涉及将消息从第三方应用程序服务器发送到设备的 Google 服务器。
Credentials
发件人 ID 与应用程序开发人员关联的电子邮件帐户。发件人 ID 用于注册过程,以识别允许向设备发送消息的 Android 应用程序。此 ID 通常是基于角色的,而不是个人帐户,例如:my-app@gmail.com。
应用程序 ID 正在注册接收消息的应用程序。应用程序通过清单中的包名来标识。这确保消息是针对正确的应用程序。
注册 ID C2DM 服务器颁发给 Android 应用程序的 ID,允许其接收消息。一旦应用程序获得注册 ID,它就会将其发送给第三方应用程序服务器,第三方应用程序服务器使用该 ID 来标识已注册接收给定应用程序消息的每个设备。换句话说,注册 ID 绑定到特定设备上运行的特定应用程序。
Google 用户帐户 为了使 C2DM 正常工作,移动设备必须包含至少一个已登录的 Google 帐户。
发件人身份验证令牌 保存在第三方应用程序服务器上的 ClientLogin 身份验证令牌,该令牌授予应用程序服务器对 Google 服务的授权访问权限。令牌包含在发送消息的 POST 请求的标头中。有关 ClientLogin 身份验证令牌的更多讨论,请参阅已安装应用程序的 ClientLogin。

生命周期流程

以下是云到设备消息传递的主要过程:

  • 启用 C2DM - 在移动设备上运行的 Android 应用程序注册以接收消息。
  • 发送消息 - 第三方应用程序服务器向设备发送消息。
  • 接收消息 - Android 应用程序从 C2DM 服务器接收消息。

来自 Android 应用程序的操作项

  1. 首先,您需要使用 C2DM 服务注册您的应用程序。 http://code.google.com/android/c2dm/signup.html
  2. 将 C2DM 集成到 Android 应用程序中,Google 将返回 RegistrationID。在 ASP.NET 应用程序中使用此 RegistrationID。 http://code.google.com/android/c2dm/index.html#writing_apps

来自 ASP.NET 应用程序的操作项

在 ASP.NET 应用程序端,我们需要以下凭据:

  • RegistrationID
  • Google 用户帐户
  • 消息文本

您的代码应遵循以下三个简单步骤来发送推送通知。

  1. 与 Google 的身份验证过程。
  2. 服务器证书验证。
  3. 提交消息。

让我们一一来看。

1. 身份验证过程

首先,您需要提供发件人 ID(Google 用户帐户名称)及其密码来获取身份验证字符串。请记住,此身份验证字符串将在我们向 C2DM 服务器提交消息时使用。

/// <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. 服务器证书

在这里,我们不会在开发工作站或应用程序服务器上安装任何证书,然后才在代码中对其进行验证。但我们对验证服务器证书进行了一些委托建模。

确保在向 C2DM 提交消息之前调用此委托方法。

//-- 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. 发送消息

最后,我们进入将推送通知发送到设备的最后一步。在成功完成以上两步后,我们必须编写以下代码来完成该过程。

现在,我们必须在这里使用 RegistrationID、Message 和 AuthenticationToken/String。

首先,创建一个 `httpWebRequest` 对象,其 URL 如代码所示。此外,我们需要将以下名称值对作为查询字符串与 URL 一起传递。

registration_id<br />collapse_key<br />delay_while_idle<br />data.payload 

(您也可以使用 `data.message` 作为备选。)

阅读下面的代码并尝试理解其实现。

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;
}

使用代码示例

您可以浏览附件中的示例代码。我已将其创建为库文件。您可以将 `AndroidPushNotification.dll` 添加到您的项目引用中并使用它。

现在,向 Android 应用程序发送推送通知只需两行代码。

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");
            }
        }
    }
}

使用 `RegistrationID`、`SenderID`、`Password` 和 `Message` 调用 `objPush.Android` 函数。

结论

我希望这段代码能让您更轻松地将 Android 推送通知与 ASP.NET 和 C# 集成。再次提醒您,您可以使用此代码运行 Android 推送通知,而无需任何服务器证书。

© . All rights reserved.