Send push notification GCM by java [closed]

2019-02-10 03:19发布

问题:

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?

回答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;


回答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);
                }

}