Get rad!

Google Cloud Messaging

Sending a notification to an Android device just keeps getting simpler and simpler. The current implementation of Google Cloud Messaging provides developers with a very simple way to send push notifications to a particular device.

What I'm going to show here is how to send a notification to a device once it's registered with your server.

I'll leave the particulars of communicating the device registration id's up to you, however the process is fairly simple:

  • Register with the GCM service on your device, retrieving a registration ID and store in the application (This can be done through our native extension).
  • Send the registration ID to your server and store it on your server as a list of connected devices
  • When you wish to send a notification, use the appropriate registration ID in the data of your message

Firstly you'll need to sign up to the Google Cloud Messaging service. This process is outlined in the "Getting Started" section on the Android developer site: http://developer.android.com/guide/google/gcm/gs.html.

You need to follow these instructions to get your API keys. If you're using our native extension in AIR then anything further can be ignored (i.e. anything from "Install the Helper Libraries"), though you will need it when developing your own native application.

Once you've got your api key and your device id you're ready to send a message. The C# code below implements a simple function that you can copy into your code.

  1. /// <summary>
  2. /// Send a Google Cloud Message. Uses the GCM service and your provided api key.
  3. /// </summary>
  4. /// <param name="apiKey"></param>
  5. /// <param name="postData"></param>
  6. /// <param name="postDataContentType"></param>
  7. /// <returns>The response string from the google servers</returns>
  8. private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
  9. {
  10. ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
  11.  
  12. //
  13. // MESSAGE CONTENT
  14. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  15.  
  16. //
  17. // CREATE REQUEST
  18. HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
  19. Request.Method = "POST";
  20. Request.KeepAlive = false;
  21. Request.ContentType = postDataContentType;
  22. Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
  23. Request.ContentLength = byteArray.Length;
  24.  
  25. Stream dataStream = Request.GetRequestStream();
  26. dataStream.Write(byteArray, 0, byteArray.Length);
  27. dataStream.Close();
  28.  
  29. //
  30. // SEND MESSAGE
  31. try
  32. {
  33. WebResponse Response = Request.GetResponse();
  34. HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
  35. if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
  36. {
  37. var text = "Unauthorized - need new token";
  38. }
  39. else if (!ResponseCode.Equals(HttpStatusCode.OK))
  40. {
  41. var text = "Response from web service isn't OK";
  42. }
  43.  
  44. StreamReader Reader = new StreamReader(Response.GetResponseStream());
  45. string responseLine = Reader.ReadToEnd();
  46. Reader.Close();
  47.  
  48. return responseLine;
  49. }
  50. catch (Exception e)
  51. {
  52. }
  53. return "error";
  54. }
  55.  
  56.  
  57. public static bool ValidateServerCertificate(
  58. object sender,
  59. X509Certificate certificate,
  60. X509Chain chain,
  61. SslPolicyErrors sslPolicyErrors)
  62. {
  63. return true;
  64. }

To use this function we simply need to assemble the postData parameter. This is a string containing the content to be sent to the google servers. There are several formats available but we'll demonstrate using JSON here. One little tip to note here is that we are using the Browser API key, not the Server API Key.

  1. string deviceId = "DEVICE_REGISTRATION_ID";
  2.  
  3. string message = "some test message";
  4. string tickerText = "example test GCM";
  5. string contentTitle = "content title GCM";
  6. string postData =
  7. "{ \"registration_ids\": [ \"" + deviceId + "\" ], "+
  8. "\"data\": {\"tickerText\":\"" + tickerText + "\", "+
  9. "\"contentTitle\":\"" + contentTitle + "\", "+
  10. "\"message\": \"" + message + "\"}}";
  11.  
  12. string response = SendGCMNotification( "YOUR_BROWSER_API_KEY", postData );

And there you have it, a simple way to send a notification to a GCM registered device. Obviously this code is only really useful for testing purposes but it should be relatively simple to integrate this into your server as required.

I've put together a sample Visual Studio solution that you can use as an example of this code here.


33 Responses to “Google Cloud Messaging using C#”

  1. When i run the code using my details i got the reponseLine =”Error=MissingRegistration”, please advice on this. Thanks in advance

    Leo

    Reply

    • @Leo

      Sounds like you haven’t specified a valid device registration id in the notification? You should retrieve a valid registration ID from a device and replace DEVICE_REGISTRATION_ID with this ID.

      Reply

      • How Can i get an Registration ID???

        Reply

        • Hi,

          The registration ID is an identifier for a device. You need setup GCM in your application and then write the necessary code in your android application to retrieve the ID from the device.

          You can use our native extension for AIR for mobile applications or refer to the Google GCM documentation for native code.

          Cheers,
          Michael

    • Have you solved this issue?if so,How did you solve it.Please revert if you have a solution.

      Reply

  2. @Michael Archbold
    Great Work. I have tested with the android emulator and real device. When I paste the emulator’s Reg. ID, I’m getting the push message correctly. But, When I try to send the push message to the real device geting the “error”:”MismatchSenderId”. Need your advice on this. Thanks in advance.

    Reply

    • This error generally occurs when you’re using the incorrect settings for your application. Double check the Sender ID and API_KEY, they must match or else you will get this error.

      Reply

  3. Hi ,
    I run the above code with a valid device registration id ,Browser API Key and SenderId(i.e. Project id).I didn’t get any error .The GCM JSON response string is in the following format
    {“multicast_id”:6703527920395624065,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1382369763829921%88cda198f9fd7ecd”}]}

    i.e. “success”:1,”failure”:0
    Still i am not able get the push notifications Message.
    Could You Please kindly advice me where is the mistake & help me out to resolve the issue.
    Thank’s
    Pradhan Prasant Kumar

    Reply

    • At a guess there is something wrong with your application side or your device isn’t correctly connected or available or your application isn’t running / registered at the time of the notification. There are so many variables its too hard for me to guess with this information.

      Michael

      Reply

    • Prasant have you found a solution for your problem?
      I’ve the same..

      Reply

    • Prasant, did you ever find a solution. I’m getting exactly the same as you.
      Thanks

      Reply

  4. Hello ,

    I am getting
    Error=InvalidRegistration
    when I use it

    Reply

    • Hi,

      You should double check your registration ID. You need to use a valid ID from a device that is using your application.

      Regards,
      Michael

      Reply

  5. Thank’s a lot that was very usefull. Congratulations.

    Reply

  6. Thanks for the code, got the notification right away! One issue I did have was the notification did not show the tickertext or contenttitle, only the message. Any idea why that would be?

    Thanks again

    Reply

  7. I am getting the following error:
    The remote server returned an error: (401) Unauthorized.

    Thanks,
    Pratham

    Reply

    • Sounds like an authorisation error. Check your certificate is correct and you have setup the Google service correctly.

      Regards,
      Michael

      Reply

  8. Hi, How can we store all the messages received into device(local DB or local storage)

    Regards,
    Manjunath T

    Reply

  9. hello,i want to send notifications to several devices,so i made List of RegistrationID-s. on WebResponse Response = Request.GetResponse(); << i got error "The remote server returned an error: (400) Bad Request. " i'm trying to send messages not from Browser,but Server.On one RegistrationID it Works perfectly. can you help me?

    Reply

    • Hi,

      The registration_ids need to be an array of the ids you are attempting to send to. So something like

      [ ID1, ID2, ID3 ]

      Cheers,
      Michael

      Reply

  10. I have an azure website which should add messages to GCM so that they are sent to an Android app. The website works when I run it locally but will not work on Azure. I have added the website IP address to the list of IPs but it still says unauthorized. How can I fix this?

    Reply

  11. I’m seeing several examples of writing GCM push notification in asp.net. I need to write an XMPP server in asp.net. I suppose duplicating the “Java sample using the Smack library” at https://developer.android.com/google/gcm/ccs.html. Have you seen any examples of how to tackle this? I would like to package it as method(s) in my existing asp.net web api server.

    Reply

    • Sorry we don’t have any experience in doing that. The C# example provided here is as far as we have experimented.

      Reply

      • OK, I ran your example with all the correct values and I got the same as Prasant.
        {“multicast_id”:6150756035177413440,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1398373764766455%1b092805f9fd7ecd”}]}
        But nothing happened in the Android app. Where am I supposed to “catch it” in the android app? my app is the demo app from the Google docs. It has a GCMBroadcastreceiver but nothing comes in there.

        Reply

      • Michael, Please disregard my recent message. I had a permission wrong. The broadcastreceiver in the android app now receives the post, even if the app is not running.

        Thanks soooo much for doing this tutorial.
        Gary

        Reply

  12. Hi Michael,
    How do we use the Server API Key and implement the server code in java
    Thanks and Regards,
    Kanthi.

    Reply

    • Hi,

      I haven’t done an implementation in Java as yet sorry. I’m sure that there is a Java example in the GCM documentation!?

      Reply

  13. I just try the code and it’s going all well except the message. my device can see a notification but there is no message , it show only ” null “

    Reply

  14. Hi, how to registered my device with c# ? This code work fine ! Thanks !

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>