Google Cloud Messaging using C#

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.

Published by

Michael

http://michaelarchbold.com

39 thoughts on “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

    1. @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.

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

  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.

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

  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

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

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

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

    1. Here is the post data…

      { “registration_ids”: [ “APA91X8i5XXXXXXXXX9pyEEGQ” ], “data”: {“tickerText”:”This is ticker text”, “contentTitle”:”This is content title”, “message”: “another test”}}

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

      Regards,
      Michael

  5. 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?

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

  6. 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?

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

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

    1. 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!?

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

  8. hello,i want to send notifications to several devices,So
    I tried [ ID1, ID2, ID3 ] But ii doesn’t work. It consider a single ID , and gives error invalid registration id.

  9. I am getting response from GCM Server and I want to check that app is installed on those device which device id is used by me. Means I want to check that app is uninstall or not from device which device id is used by me.

    Thanks…

  10. hi i got issue like “The remote server returned an error: (401) Unauthorized.” please give the solution

  11. Hi!
    Both the Browser API key and the Server API Key work. I have tested today (2015/07/04).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>