Send push notification GCM by java

20,803

Solution 1

You can use gcm-server.jar which contains helper methods for GCM messaging. To get this jar you can install "[Deprecated]Google Cloud Messaging for Android Library" through Android SDK Manager. Don't let the deprecated name confuse you. Only the client part is deprecated, not server side.
After install you can find it at "ADT_SDKROOT\sdk\extras\google\gcm". The sample folder contains a demo server which is very easy to understand.
Sending a GCM message involves only few lines of code:

    final String GCM_API_KEY = "yourKey";
    final int retries = 3;
    final String notificationToken = "deviceNotificationToken";
    Sender sender = new Sender(GCM_API_KEY);
    Message msg = new Message.Builder().build();

    try {
                Result result = sender.send(msg, notificationToken, retries);

                if (StringUtils.isEmpty(result.getErrorCodeName())) {
                    logger.debug("GCM Notification is sent successfully");
                    return true;
                }

                logger.error("Error occurred while sending push notification :" + result.getErrorCodeName());
    } catch (InvalidRequestException e) {
                logger.error("Invalid Request", e);
    } catch (IOException e) {
                logger.error("IO Exception", e);
    }
    return false;

Solution 2

For """test""" create java console app, add gcm jar file.

    try{
     Sender sender = new Sender("<senderId>");
     ArrayList<String> devicesList = new ArrayList<String>();
     devicesList.add(<deviceId>);
     String data = "<data>";
     Message message = new Message.Builder()
                        .collapseKey("1")
                        .timeToLive(3)
                        .delayWhileIdle(true)
                        .addData("message",
                                data)
                        .build();
    MulticastResult result = sender.send(message, devicesList, 1);
                sender.send(message, devicesList, 1);

                System.out.println(result.toString());
                if (result.getResults() != null) {
                    int canonicalRegId = result.getCanonicalIds();
                    if (canonicalRegId != 0) {
                    }
                } else {
                    int error = result.getFailure();
                    System.out.println(error);
                }

}
Share:
20,803
user3302527
Author by

user3302527

Updated on February 19, 2020

Comments

  • user3302527
    user3302527 about 4 years

    I have configured a client android Google Cloud Messaging (GCM) to receive push notifications, but I can not configure a server in java to send notifications to devices. How could I?

  • user3302527
    user3302527 about 10 years
    It worked. thank you!
  • sinujohn
    sinujohn about 10 years
    if it worked, you should consider accepting the answer. It'll be useful to others :)
  • Jugal Panchal
    Jugal Panchal almost 10 years
    It is what I was looking, thank buddy you have saved my time. :)
  • LoveMeSomeFood
    LoveMeSomeFood over 9 years
    Hi I tried this using Eclipse and got this error. Any idea how to solve this? Exception in thread “main” java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException at NotificationSenderClass.main(NotificationSenderClass.java:16‌​) Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306)...
  • LoveMeSomeFood
    LoveMeSomeFood over 9 years
    I downloaded the gcm.server.jar file and added it as library. Thanks in advance!
  • vivex
    vivex almost 9 years
    Where i have to pass my projectID ? GCMRegID of receiver device?