0

How to send extras from server side like userId or eventId using c2dm and get from my android application in onMessage() function ?

This is SendMessage on server side function C#

private static void SendMessage(string authTokenString, string registrationId, string message)
    {
        //Certeficate was not being accepted for the sercure call
        //ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GoogleMessageUrl);
        request.Method = PostWebRequest;
        request.KeepAlive = false;

        NameValueCollection postFieldNameValue = new NameValueCollection();
        postFieldNameValue.Add(RegistrationIdParam, registrationId);
        postFieldNameValue.Add(CollapseKeyParam, "0");
        postFieldNameValue.Add(DelayWhileIdleParam, "0");
        postFieldNameValue.Add(DataPayloadParam, 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=" + authTokenString);

        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;
        if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
        {
            Console.WriteLine("Unauthorized - need new token");
        }
        else if (!responseCode.Equals(HttpStatusCode.OK))
        {
            Console.WriteLine("Response from web service not OK :");
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        }

        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseLine = reader.ReadLine();
        reader.Close();
    }
FlorinD
  • 481
  • 2
  • 8
  • 25

1 Answers1

0

In c2dm you can send your own data in the data.<key> POST fields from the server, e.g. you could do:

postFieldNameValue.Add("data.userid", theUserId);
postFieldNameValue.Add("data.eventid", theEventId);

Make sure that the strings you send (theUserId and theEventId) are URL encoded.

The Android client can fetch the data in the onMessage(Context context, Intent intent) method with:

Bundle extras = intent.getExtras();
String theUserId = extras.getString("userid");
String theEventId = extras.getString("eventid");

More in depth explanation can be found in this tutorial

johlo
  • 5,422
  • 1
  • 18
  • 32