Friday 15 March 2013

Android Google Cloud Messaging Server Side Code

GCM Server Side Application:

To create server side application, follow these steps:

1. Create a new java project as:


2. Enter name for new java project e.g. NotificationServer


3. Click on Next button. Add gcm-server.jar library and json-simple-1.1.1.jar library to this project by clicking on Add External JARs button. Specify your path of libraries to add to project.Then click on Finish button.


4. New java project is created now and available in Project Explorer.


5. Now create a package, by right click on src->new->package as:

6. Enter name of package and click on Finish button.


7. Now after creating package, add a class GCMServer to package and click on Finish button.


8. Finally, write the actual code to java project i.e. server side code. Here is complete code for server side implementation on java.


package com.push.notification.server;

import java.util.ArrayList;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

public class GCMServer {

    public static void main(String args[]) {

        new Thread(){

            public void run(){
    
                try {
                    //Please add here your project API key: "Key for browser apps (with referers)".
                    //If you added "API key Key for server apps (with IP locking)" or "Key for Android apps (with certificates)" here
                    //then you may get error responses.
                    Sender sender = new  Sender("AIzaSyB7Ej255tpTaemk_-Ljmn4GcklldT14Hp4");

                    // use this to send message with payload data
                    Message message = new Message.Builder()
                    .collapseKey("message")
                    .timeToLive(3)
                    .delayWhileIdle(true)
                    .addData("message", "Welcome to Push Notifications") //you can get this message on client side app
                    .build(); 
 
                    //Use this code to send notification message to a single device
                    Result result = sender.send(message,
                            "APA91bEbKqwTbvvRuc24vAYljcrhslOw-jXBqozgH8C2OB3H8R7U00NbIf1xp151ptweX9VkZXyHMik022cNrEETm7eM0Z2JnFksWEw1niJ2sQfU3BjQGiGMq8KsaQ7E0jpz8YKJNbzkTYotLfmertE3K7RsJ1_hAA",
                            1);
                    System.out.println("Message Result: "+result.toString()); //Print message result on console

                    //Use this code to send notification message to multiple devices
                    ArrayList<String> devicesList = new ArrayList<String>();
                    //add your devices RegisterationID, one for each device               
                    devicesList.add("APA91bEbKqwTbvvRuc24vAYljcrhslOw-jXBqozgH8C2OB3H8R7U00NbIf1xp151ptweX9VkZXyHMik022cNrEETm7eM0Z2JnFksWEw1niJ2sQfU3BjQGiGMq8KsaQ7E0jpz8YKJNbzkTYotLfmertE3K7RsJ1_hAA");   
                    devicesList.add("APA91bEVcqKmPnESzgnGpEstHHymcpOwv52THv6u6u2Rl-PaMI4mU3Wkb9bZtuHp4NLs4snBl7aXXVkNn-IPEInGO2jEBnBI_oKEdrEoTo9BpY0i6a0QHeq8LDZd_XRzGRSv_R0rjzzZ1b6jXY60QqAI4P3PL79hMg");   

                    //Use this code for multicast messages   
                    MulticastResult multicastResult = sender.send(message, devicesList, 0);
                    System.out.println("Message Result: "+multicastResult.toString());//Print multicast message result on console

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();   
    }
}

9. Copy this code to your project and then click on Run button to execute this java project.

This is all what you need to do on server side.For client end code please refer to "Google Cloud Messaging (GCM) Client Code".

In case of any query please don't hesitate to contact.
Please don't forget to give your feedback. Thanks.

































53 comments:

  1. hello...
    i create gcm client application which persent in sdk sample for gcm in that folder server gcm is present how to use that file for server side code i anable to import that file to my work space

    ReplyDelete
    Replies
    1. well, for server side code you need to create java project manually in your workspace. simply follow above procedure. did you implemented onMessage method in client application? please tell more specific detail.

      Delete
  2. well, for server side code you need to create java project manually in your workspace. simply follow above procedure. did you implemented onMessage method in client application? please tell more specific detail.

    ReplyDelete
  3. @Ajay

    ProxyHost will be local IP address of your system.

    You can also skip proxyhost part by adding following two statements instead:
    System.set property("https.nonProxyHosts",""web cache.my domain.com");
    System.setProperty("https.proxyPort","");

    Sorry for late reply...

    ReplyDelete
  4. i am getting "com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401" error.can you help me.

    ReplyDelete
    Replies
    1. Suresh..
      Please check
      1. whether you entered valid api-key in your gcm server code?
      2. Enter your local system IP for proxyhost.
      3. Did you enable "Google cloud messaging for android" service using Google APIs Console?

      Please feel free to contact me.

      Delete
  5. I also gave : this below sample code

    System.set property("https.nonProxyHosts",""");
    System.setProperty("https.proxyPort","");

    still i got same error Pls tel me correct thing ...
    i request to ask could you please tel me how can i get my proxyHost.

    ReplyDelete
  6. in client app i got message is null

    ReplyDelete
    Replies
    1. Saran..

      I already mentioned that proxyhost will be local IP address of your PC on which your gcm server project is running.
      Try this else show me your compelete gcm server code.

      Delete
  7. Dear Syed,

    Thanks for this post. Actually i need to build enable Push Notification in my android App...

    Pl help me how to start as i am newbie in android.

    How to Write server side code to register device to the GCM server.
    How to write code for sending push notification.

    ReplyDelete
    Replies
    1. Hi,

      Thanks for visiting this blog.

      Well, I wrote another post for newbies. First, you have to follow Register Android Project post then follow GCM Server Side post.

      In case of any concern please feel free to contact me.

      Delete
  8. hi syed! thank you for the server side app.. can you please send client side code.. you will help a lot.. because i find this for long time now.. i am new in android..thank you

    ReplyDelete
  9. above code is server client?
    i am create client but how to create server and deploy?
    help us

    ReplyDelete
  10. realy nice this code can i use within GWT?
    rply pls

    ReplyDelete
  11. com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401
    at below line..

    String regId = "APA91bEeVCFiyVbmj7gh27a4kSWAOP2lnDWnUH80lQl2tXqVwtP16paoyBNEiJ2oJfPJqJnbKWGQ0eCD2I4qAmtOceDSuNMifTzkM55-ZxIFe5c1b6BYVIQwK37X_1R-mAwMDXaQjBNVMy-icS4MOVDt-VOHQ";

    //Use this code to send notification message to a single device
    Result result = sender.send(message, regId, 1);

    ReplyDelete
  12. can you provide client side code also.???

    ReplyDelete
  13. pls give project files in downloadable format....

    thanks in advance

    ReplyDelete
  14. I want need to create upstream in GSM using with CCS .. but currently i have gcm client in my sdk and i use json with HTTP what i need to create server side in my application and how to implement both in my project.. i wnat step by step procedure to create....

    ReplyDelete
  15. import com.google.android.gcm.server.Message;
    import com.google.android.gcm.server.MulticastResult;
    import com.google.android.gcm.server.Result;
    import com.google.android.gcm.server.Sender;

    in this code i got error at all pakages. how ca i solve this?


    ReplyDelete
    Replies
    1. Hi Seeni Vasan,

      Sorry for late reply, you need to add gcm.jar library in your project. You can add gcm library by Right Click on your Project -> Click Properties ->Java Build Path -> Libraries -> Add External JARs ->(Path of gcm.jar library). After adding library, you will not see such errors any more.

      In case of any concern please do not hesitate to contact me.



      Delete
  16. currently i am using XAMPP with eclipse ADT in my project, i Refereed some Sites i got some information such as need to install 1. TLS/SSL with xammp.. 2. must use ccs for upstream [ send message from device to server ] .. but i HTTP with json in my client side code.. how to implement css server side code with project. i need step by step procedure to create .. my mail id : sureshbecse88@gmail.com

    ReplyDelete
  17. Really superb tutorial.. 5/5 star.. keep doing :)

    ReplyDelete
  18. I got error.
    javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty.
    if there is any possible to send with out ssl certificate.

    ReplyDelete
    Replies
    1. Hi Yoharaja, I have uploaded complete source code for GCM Server and Client yesterday. You can download and use that. Please see my post "Google Cloud Messaging (GCM) Client Code" for source code. In case of any concern please feel free to contact me. Thank you.

      Delete
    2. @Yoharaja Dhanabalan , Hi I am also getting same issue, Please share solution if you have already resolved it. Thanks

      Delete
  19. Hi Sanjay,
    Please download complete source code for Server and Client end from my post "Google Cloud Messaging (GCM) Client Code". It is available under 2015 -> February. In case of any concern please feel free to coordinate.
    Thank you

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. hello i got this error . .

    java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
    at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:275)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:371)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1091)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
    at com.google.android.gcm.server.Sender.post(Sender.java:479)
    at com.google.android.gcm.server.Sender.post(Sender.java:458)
    at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:170)
    at com.google.android.gcm.server.Sender.send(Sender.java:121)
    at com.ServerG.gcmServer$1.run(gcmServer.java:33)

    ReplyDelete
  22. Hi,

    Is it necessary to store each device's ID in DB at the server end??

    ReplyDelete
    Replies
    1. Hi Vipul,
      It's up to your requirement. If you want server broadcast message(s) to each device then you need to store it in DB.

      Delete
  23. Where can I get gym-server.jar. Could you please provide a link ?

    ReplyDelete
    Replies
    1. Hi Venu,here is the link.
      http://www.java2s.com/Code/Jar/g/Downloadgcmserverjar.htm

      Delete
  24. Your current account (dheerajbansal.90@gmail.com) does not have access to view this page.
    Click here to logout and change accounts.
    when I want to access client end code.

    ReplyDelete
  25. Hi!

    What about upstream messages? How could it be implemented on both sides: server and client?

    ReplyDelete
    Replies
    1. Hi césar Retana,

      Sorry, I didn't get your point. Would you please share some specific details?

      Delete
  26. super, it's worked for me, thanks alot

    ReplyDelete
  27. Hi,
    I want change the gcm message format, like add icons and images in message. is it possible

    ReplyDelete
    Replies
    1. Hi Sagar,
      It is very easy to implement this.
      Please see my post:
      http://myandroidpoint.blogspot.com/2014/04/custom-push-notifications_26.html

      In case of any concern please feel free to contact me.
      Cheers!

      Delete
  28. hello friend, me I liked your post is very interesting .
    Tell me where to find the part of the client code . Thank you very much

    ReplyDelete
    Replies
    1. Hi Juan, Thanks for visiting my blog. Here is the client code.
      http://myandroidpoint.blogspot.com/2015/02/google-cloud-messaging-gcm-client-code.html

      In case of any concern please do let me know.
      Cheers!

      Delete
  29. hello friend, me I liked your post is very interesting .
    Tell me where to find the part of the client code . Thank you very much

    ReplyDelete
    Replies
    1. Hi, Here is the client side complete code:
      http://myandroidpoint.blogspot.com/2015/02/google-cloud-messaging-gcm-client-code.html

      Thank you

      Delete
  30. after saving registration key in db then above code can i use. to send notification to device

    ReplyDelete
  31. I'm getting the following error........ what to do now ?

    Message Result: [ errorCode=MismatchSenderId ]
    Message Result: MulticastResult(multicast_id=5978335447717560210,total=1,success=1,failure=0,canonical_ids=0,results: [[ messageId=0:1469524154387556%4995891738eb0007 ]]

    ReplyDelete
    Replies
    1. this problem got solved

      Delete
    2. can u please tell me how u solved it

      Delete
  32. when the screen is locked. I'm not getting push notifications.

    ReplyDelete
  33. @pradeep or @Syed please tell me how to solve the error Message Result: [ errorCode=MismatchSenderId ]

    ReplyDelete
    Replies
    1. Hi Rajiv, sorry for late reply. MismatchSenderId clearly states there is some issue with SENDER ID. Please look at the following, it might help you.
      http://stackoverflow.com/questions/11307689/when-sending-messages-using-gcm-i-keep-getting-the-response-mismatchsenderid

      Thank you

      Delete
  34. Saranya, Thank you so much for your feedback.

    ReplyDelete
  35. Geetha, Thank you for your kind words.

    ReplyDelete