4

I am working on an android application which uses push notification service by GCM. Currently I am stuck at creating a server. The guides provided by the GCM documentation is in java which I have no idea how to implement. After researching for awhile, I found GCMSharp on github which uses C#

PushSharp - https://github.com/Redth/PushSharp

But as of now, I am new to creating a server and have no idea how to get started. Is the server actually a web service that keeps listening to request and upon getting a request directs it to the GCM which pushes notification to the client phone?

And if yes, do I implement it in a webservice such as WCF?

user2857001
  • 85
  • 1
  • 3
  • 7

2 Answers2

5

You could follow this tutorial.

Is the server actually a web service that keeps listening to request and upon getting a request directs it to the GCM which pushes notification to the client phone?

You don't need to listen to requests. GCM Push directly pushes any message to the device without any request. For more details, Read this documentation.

Mangesh
  • 5,491
  • 5
  • 48
  • 71
Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
  • If that is the case, what is the use of implementing a server? In the documentation it writes: A 3rd-party application server that you must implement. This application server sends data to a GCM-enabled Android application via the chosen GCM connection server. Isn't the server we implement the one that sends the message? – user2857001 Oct 08 '13 at 07:31
  • All that you need to do in the backend is to collect device tokens from the android devices as the users gets registered to GCM server and save them in your DB. When you want to push a message, you can ask Google Server to send your message using device tokens and your Api key. – Seshu Vinay Oct 08 '13 at 07:34
  • Ohh! So is the server just for registering the deviceID and retrieving the deviceID. And for sending from device A to device B, Device A will get Device B's ID from the server and just push the notification using GCM to device B? – user2857001 Oct 08 '13 at 07:42
  • GCM is not for sending message from device A to device B. Its for pushing message from Server to device. However, you can build a messaging system using GCM. But it's not effective and efficient. You might use XMPP Server to send message from device A to device B. – Seshu Vinay Oct 08 '13 at 07:45
1

I have answered to this on another thread and here i am repeating. Code looks bit longer but it works. I just sent a push notification to my phone after struggling 2 days by implementing the following code in C# project. I referred a link regarding this implementation, But couldn't find it to post here. So will share my code with you. If you want to test the Notification online you may visit to this link.

note : I have hardcorded apiKey, deviceId and postData, please pass the apiKey,deviceId and postData in your request and remove them from the method body. If you want pass message string also

public string SendGCMNotification(string apiKey, string deviceId, string postData)
{
    string postDataContentType = "application/json";
    apiKey = "AIzaSyC13...PhtPvBj1Blihv_J4"; // hardcorded
    deviceId = "da5azdfZ0hc:APA91bGM...t8uH"; // hardcorded

    string message = "Your text";
    string tickerText = "example test GCM";
    string contentTitle = "content title GCM";
    postData =
    "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
      "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
                 "\"contentTitle\":\"" + contentTitle + "\", " +
                 "\"message\": \"" + message + "\"}}";


    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

    //
    //  MESSAGE CONTENT
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    //
    //  CREATE REQUEST
    HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
    Request.Method = "POST";
    Request.KeepAlive = false;
    Request.ContentType = postDataContentType;
    Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
    Request.ContentLength = byteArray.Length;

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

    //
    //  SEND MESSAGE
    try
    {
        WebResponse Response = Request.GetResponse();
        HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
        if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
        {
            var text = "Unauthorized - need new token";
        }
        else if (!ResponseCode.Equals(HttpStatusCode.OK))
        {
            var text = "Response from web service isn't OK";
        }

        StreamReader Reader = new StreamReader(Response.GetResponseStream());
        string responseLine = Reader.ReadToEnd();
        Reader.Close();

        return responseLine;
    }
    catch (Exception e)
    {
    }
    return "error";
}

public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
    return true;
}

You may not familiar with words like apiKey, deviceId. Dont worry i will explain what are they and how to create those.

apiKey
What & why :This a key that will be used when sending requests to GCM server.
How to create : Refer this post

deviceId
What & why : This id also known as RegistrationId. This is a unique id to identify the device. When you want to send a notification to a specific device you need this id.
How to create: This depends on how you implement the application. For cordova i used a simple pushNotification Plugin You can simply create a deviceId/RegistrationId using this plugin. To do that you need to have a senderId. Google how to create a senderId it is really simple =)

If anyone needs some help leave a comment.

Happy Coding.
-Charitha-

Community
  • 1
  • 1
Charitha Goonewardena
  • 4,418
  • 2
  • 36
  • 38