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.
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.
hello...
ReplyDeletei 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
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.
Deletewell, 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.
ReplyDeleteHow i get the proxyHost
ReplyDelete@Ajay
ReplyDeleteProxyHost 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...
i am getting "com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401" error.can you help me.
ReplyDeleteSuresh..
DeletePlease 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.
I also gave : this below sample code
ReplyDeleteSystem.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.
in client app i got message is null
ReplyDeleteSaran..
DeleteI 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.
Dear Syed,
ReplyDeleteThanks 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.
Hi,
DeleteThanks 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.
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
ReplyDeleteabove code is server client?
ReplyDeletei am create client but how to create server and deploy?
help us
realy nice this code can i use within GWT?
ReplyDeleterply pls
com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401
ReplyDeleteat 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);
can you provide client side code also.???
ReplyDeletepls give project files in downloadable format....
ReplyDeletethanks in advance
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....
ReplyDeleteimport com.google.android.gcm.server.Message;
ReplyDeleteimport 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?
Hi Seeni Vasan,
DeleteSorry 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.
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
ReplyDeleteReally superb tutorial.. 5/5 star.. keep doing :)
ReplyDeletesathish, Thank you very much for feedback.
DeleteI got error.
ReplyDeletejavax.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.
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@Yoharaja Dhanabalan , Hi I am also getting same issue, Please share solution if you have already resolved it. Thanks
DeleteHi Sanjay,
ReplyDeletePlease 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
This comment has been removed by the author.
ReplyDeletehello i got this error . .
ReplyDeletejava.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)
Hi,
ReplyDeleteIs it necessary to store each device's ID in DB at the server end??
Hi Vipul,
DeleteIt's up to your requirement. If you want server broadcast message(s) to each device then you need to store it in DB.
Where can I get gym-server.jar. Could you please provide a link ?
ReplyDeleteHi Venu,here is the link.
Deletehttp://www.java2s.com/Code/Jar/g/Downloadgcmserverjar.htm
Your current account (dheerajbansal.90@gmail.com) does not have access to view this page.
ReplyDeleteClick here to logout and change accounts.
when I want to access client end code.
Hi!
ReplyDeleteWhat about upstream messages? How could it be implemented on both sides: server and client?
Hi césar Retana,
DeleteSorry, I didn't get your point. Would you please share some specific details?
super, it's worked for me, thanks alot
ReplyDeleteHi,
ReplyDeleteI want change the gcm message format, like add icons and images in message. is it possible
Hi Sagar,
DeleteIt 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!
hello friend, me I liked your post is very interesting .
ReplyDeleteTell me where to find the part of the client code . Thank you very much
Hi Juan, Thanks for visiting my blog. Here is the client code.
Deletehttp://myandroidpoint.blogspot.com/2015/02/google-cloud-messaging-gcm-client-code.html
In case of any concern please do let me know.
Cheers!
hello friend, me I liked your post is very interesting .
ReplyDeleteTell me where to find the part of the client code . Thank you very much
Hi, Here is the client side complete code:
Deletehttp://myandroidpoint.blogspot.com/2015/02/google-cloud-messaging-gcm-client-code.html
Thank you
after saving registration key in db then above code can i use. to send notification to device
ReplyDeleteI'm getting the following error........ what to do now ?
ReplyDeleteMessage Result: [ errorCode=MismatchSenderId ]
Message Result: MulticastResult(multicast_id=5978335447717560210,total=1,success=1,failure=0,canonical_ids=0,results: [[ messageId=0:1469524154387556%4995891738eb0007 ]]
this problem got solved
Deletecan u please tell me how u solved it
Deletewhen the screen is locked. I'm not getting push notifications.
ReplyDelete@pradeep or @Syed please tell me how to solve the error Message Result: [ errorCode=MismatchSenderId ]
ReplyDeleteHi Rajiv, sorry for late reply. MismatchSenderId clearly states there is some issue with SENDER ID. Please look at the following, it might help you.
Deletehttp://stackoverflow.com/questions/11307689/when-sending-messages-using-gcm-i-keep-getting-the-response-mismatchsenderid
Thank you
Saranya, Thank you so much for your feedback.
ReplyDeleteGeetha, Thank you for your kind words.
ReplyDelete