Click here to Skip to main content
Click here to Skip to main content
Go to top

Android push notification implementation using ASP.NET and C#

, 10 Apr 2012
Rate this:
Please Sign up or sign in to vote.
Just three steps to implement Android push notification and it is easy and simple.

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.
Components
Mobile Device The device that is running an Android application that uses C2DM. This must be a 2.2 Android device that has Market installed, and it must have at least one logged-in Google account.
Third Party Application Server An application server that developers set up as part of implementing C2DM in their applications. The third-party application server sends data to an Android application on the device via the C2DM server.
C2DM Server The Google servers involved in taking messages from the third-party application server and sending them to the device.
Credentials
Sender ID An email account associated with the application's developer. The sender ID is used in the registration process to identify an Android application that is permitted to send messages to the device. This ID is typically role-based rather than being a personal account—- for example, my-app@gmail.com.
Application ID The application that is registering to receive messages. The application is identified by the package name from the manifest. This ensures that the messages are targeted at the correct application.
Registration ID An ID issued by C2DM servers to the Android application that allows it to receive messages. Once the application has the registration ID, it sends it to the third-party application server, which uses it to identify each device that has registered to receive messages for a given application. In other words, a registration ID is tied to a particular application running on a particular device.
Google User Account For C2DM to work, the mobile device must include at least one logged-in Google account.
Sender Auth Token A ClientLogin Auth token that is saved on the third-party application server that gives the application server authorized access to Google services. The token is included in the header of POST requests that sends messages. For more discussion of ClientLogin Auth tokens, see ClientLogin for Installed Applications.

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

  1. First you need to register your application with C2DM services. http://code.google.com/android/c2dm/signup.html
  2. 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.

  1. Authentication process with Google.
  2. Server certification validation.
  3. 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.

/// <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.

//-- 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.

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.

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.dll to your project reference and use it.

To send a push notification to the Android application is now just two lines of code.

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)

Share

About the Author

Vimal Panara
Technical Lead IndiaNIC Infotech Ltd
India India
No Biography provided

Comments and Discussions

 
QuestionThe remote server returned an error: (401) Unauthorized. Pinmemberahmed.sharu3-Aug-13 4:34 
GeneralMy vote of 5 Pinmemberravithejag1-Jul-13 0:48 
QuestionThe remote server returned an error: (401) Unauthorized. PinmemberEllaiyaraja13-May-13 4:14 
AnswerRe: The remote server returned an error: (401) Unauthorized. Pinmemberahmed.sharu3-Aug-13 4:31 
Questionsend notification based on user PinmemberZapss7-May-13 2:34 
SuggestionVery Nice article PinmemberJaydeep Jadav18-Dec-12 1:27 
Questionquestion Pinmemberkparth26-Jul-12 6:25 
GeneralMy vote of 5 Pinmembergeeman442-Jul-12 6:42 
QuestionBrother Nice article ! But i am getting Unauthorized - 401 continuously. I have implemented it using OAuth 2.0. PinmemberBhuvinT22-Jun-12 1:46 
AnswerRe: Brother Nice article ! But i am getting Unauthorized - 401 continuously. I have implemented it using OAuth 2.0. PinmemberEllaiyaraja13-May-13 2:09 
QuestionDude could you provide the implementation for OAuth 2.0 since the client id method is already deprecated PinmemberBhuvinT21-Jun-12 2:39 
GeneralThank you Vimal Pinmembernsandeep8720-Jun-12 0:05 
QuestionSample code ir a .rar PinmemberLuizBaglieMnix6-Jun-12 5:56 
QuestionYep, appears as thought he ZIPfile is corrupted Pinmemberadsaero15-May-12 1:20 
QuestionThe download zip is corrupted PinmemberMember 405238411-May-12 6:21 
AnswerRe: The download zip is corrupted PinmemberVimal Panara21-May-12 23:52 
QuestionResponse = id=0:1335279222726793%99e5873500000031 Pinmemberjilanisk0924-Apr-12 4:55 
QuestionI want to learn C# when I read this! Pinmembersun mi Kang11-Apr-12 19:27 
QuestionI would investigate a replacement to PinmemberBassam Saoud10-Apr-12 9:24 
GeneralNice Article Pinmembersupernova566610-Apr-12 9:23 
QuestionAndroid push notification implementation using ASP.NET C# Pinmembermita vaghela124-Mar-12 2:08 
AnswerRe: Android push notification implementation using ASP.NET C# Pinmembermita vaghela124-Mar-12 3:09 
QuestionResponse is good but no actual message received [modified] PinmemberShiju Abraham14-Mar-12 12:11 
AnswerRe: Response is good but no actual message received PinmemberVimal Panara25-Mar-12 23:42 
AnswerRe: Response is good but no actual message received PinmemberVimal Panara25-Mar-12 23:54 
QuestionRequest for uploading Java PinmemberTin Maung13-Mar-12 19:15 
AnswerRe: Request for uploading Java PinmemberVimal Panara25-Mar-12 23:43 
Questionzip is broken - is there a definition for GetPostStringFrom? Pinmembervalensmobile13-Mar-12 12:23 
AnswerRe: zip is broken - is there a definition for GetPostStringFrom? PinmemberVimal Panara25-Mar-12 23:44 
QuestionVery good PinmemberGeir Danielsen13-Mar-12 3:19 
AnswerRe: Very good PinmemberVimal Panara25-Mar-12 23:46 
GeneralMy vote of 5 Pinmembermarcoingegneri7-Mar-12 0:39 
GeneralMy vote of 5 PinmemberАslam Iqbal5-Mar-12 18:49 
QuestionWhy would you do this, totally useless! PinmemberBill SerGio, The Infomercial King3-Mar-12 5:26 
AnswerRe: Why would you do this, totally useless! PinmemberVimal Panara5-Mar-12 2:26 
AnswerRe: Why would you do this, totally useless! PinmemberJonathan C Dickinson5-Mar-12 22:21 
AnswerRe: Why would you do this, totally useless! PinmemberEldon Elledge14-Mar-12 6:21 
AnswerRe: Why would you do this, totally useless! PinmemberIannick19-Apr-12 5:23 
GeneralMy vote of 5 Pinmembermaq_rohit2-Mar-12 23:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 10 Apr 2012
Article Copyright 2012 by Vimal Panara
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid