且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过java发送推送通知GCM

更新时间:2023-01-02 23:27:56

您可以使用 gcm-server.jar 包含用于 GCM 消息传递的辅助方法.要获取此 jar,您可以通过 Android SDK 管理器安装[已弃用]Google Cloud Messaging for Android Library".不要让弃用的名称使您感到困惑.只有客户端部分被弃用,而不是服务器端.
安装后,您可以在 "ADT_SDKROOTsdkextrasgooglegcm" 找到它.示例文件夹包含一个非常容易理解的演示服务器.
发送 GCM 消息只涉及几行代码:

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_SDKROOTsdkextrasgooglegcm". 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;