如何使用C2DM向多个用户发送推送消息?

时间:2012-06-27 10:51:22

标签: android android-c2dm

到目前为止,我已成功使用注册ID和具有签名C2DM角色帐户的authtoken向一台设备发送消息。现在我已经向多个用户发送消息。我不知道如何实现这一目标。

任何人都可以帮助克服这个问题。

Java Servlet代码,

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {


        resp.setContentType("text/plain");
        StringBuilder data = new StringBuilder();

        data.append("registration_id=" + ServerConfig.DeviceRegistrationID_S);

        // Collapse key is for grouping messages and only the last sent message
        // with the same key going to be sent to the phone when the phone is
        // ready to get the message if its not from the beginning
        data.append("&collapse_key=test");



        // Here is the message we sending, key1 can be changed to what you whant
        // or if you whant to send more then one you can do (i think, not tested
        // yet), Testing is the message here.
        data.append("&data.key1=Testing Message from C2DM");

        // If you want the message to wait to the phone is not idle then set
        // this parameter

// data.append(“& delay_while_idle = 1”);

        byte[] postData = data.toString().getBytes("UTF-8");

        StringBuilder sb = new StringBuilder();

        sb.append(ServerConfig.AuthToken + " - ");

        try {
            // Send data
            URL url = new URL("https://android.clients.google.com/c2dm/send");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Content-Length",
                    Integer.toString(postData.length));
            conn.setRequestProperty("Authorization", "GoogleLogin auth="
                    + ServerConfig.AuthToken);

            OutputStream out = conn.getOutputStream();
            out.write(postData);
            out.close();

            Integer responseCode = conn.getResponseCode();
            if (responseCode.equals(503)) {
                // the server is temporarily unavailable
                sb.append("responseCode = " + responseCode);
            } else {
                if (responseCode.equals(401)) {
                    // AUTH_TOKEN used to validate the sender is invalid
                    sb.append("responseCode = " + responseCode);
                } else {
                    if (responseCode.equals(200)) {

                        // Check for updated token header
                        String updatedAuthToken = conn
                                .getHeaderField("Update-Client-Auth");
                        if (updatedAuthToken != null) {
                            ServerConfig.AuthToken = updatedAuthToken;
                            sb.append("updatedAuthToken = \""
                                    + updatedAuthToken + "\"");
                        }

                        String responseLine = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()))
                                .readLine();

                        if (!sb.toString().equals("")) {
                            sb.append(" - ");
                        }

                        if (responseLine == null || responseLine.equals("")) {
                            sb.append("Got responsecode "
                                    + responseCode
                                    + " but a empty response from Google AC2DM server");
                        } else {
                            sb.append(responseLine);
                        }
                    } else {
                        sb.append("responseCode = " + responseCode);
                    }
                }
            }
        } catch (Exception e) {
            if (!sb.toString().equals("")) {
                sb.append(" - ");
            }

            sb.append("Exception: " + e.toString());
        }

        resp.getWriter().println(sb.toString());

    }

1 个答案:

答案 0 :(得分:0)

我知道你正在处理C2DM,但谷歌刚刚发布了C2dM后继者GCM,它允许在一个HTTP帖子中向1000个设备发送通知。如果您的应用尚未上市,我建议您在部署之前立即迁移到使用GCM。向GCM中的多个设备发布通知非常简单,只需将所有设备注册ID放入JSON阵列并将其发送到谷歌服务器,如下所示:

{ 
  "registrations_ids": [reg_id1, reg_id2, reg_id3, reg_id10, reg_id100],
  "data" : "payload"
}

但是如果你坚持使用C2DM,你只需循环发送通知,迭代设备注册ID。