【问题标题】:CM getting Canonical IDCM 获取规范 ID
【发布时间】:2014-07-04 08:18:52
【问题描述】:

我是 GCM 新手,不知道如何从响应中获取 Cannonical Id。这是我读到的:

GCM 提供了一种称为“规范注册 ID”的工具,可以轻松地 从这些情况中恢复过来。定义了一个规范的注册 ID 作为您的应用程序请求的最后一次注册的 ID。 这是服务器在向服务器发送消息时应使用的 ID 设备。

如果您稍后尝试使用其他注册方式发送消息 ID,GCM 将照常处理请求,但它将包含 的registration_id字段中的规范注册ID 回应。确保替换存储在您的注册 ID 具有此规范 ID 的服务器,因为最终您使用的 ID 将 停止工作。

这是我从服务器向设备发送 GCM 消息的功能:

    private string SendMessageUsingGCM(String sGCMRegistration, string sMessage, string sCollapseKey)
    {
        String GCM_URL = @"https://android.googleapis.com/gcm/send";

        bool flag = false;
        string sError = "";
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("registration_id={0}&collapse_key={1}", sGCMRegistration, sCollapseKey);
        sb.AppendFormat("&time_to_live=30&delay_while_idle=0"); //Para que se reciba cuanto antes
        sb.AppendFormat("&data.msg=" + sMessage);

        string msg = sb.ToString();
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GCM_URL);
        req.Method = "POST";
        req.ContentLength = msg.Length;
        req.ContentType = "application/x-www-form-urlencoded";

        req.Headers.Add("Authorization:key=" + sGcmApiKey); //Here goes my Api Key 

        using (StreamWriter oWriter = new StreamWriter(req.GetRequestStream()))
        {
            oWriter.Write(msg);
        }

        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string respData = sr.ReadToEnd();

                if (resp.StatusCode == HttpStatusCode.OK)   // OK = 200
                {
                    if (respData.StartsWith("id="))
                        flag = true;
                    else
                        sError = respData;
                }
                else if (resp.StatusCode == HttpStatusCode.InternalServerError)   // 500
                    sError = "Internal server error. Try later.";
                else if (resp.StatusCode == HttpStatusCode.ServiceUnavailable)    // 503
                    sError = "Server not available temnporatily. Try later.";
                else if (resp.StatusCode == HttpStatusCode.Unauthorized)          // 401
                    sError = "The API Key is not valid.";
                else
                    sError = "Error: " + resp.StatusCode;
            }
        }

        if (flag == true)
            return "1";

        return "0 " + sError;
    }

那么,如何在响应的 registration_id 字段中获取规范注册 ID?

谢谢

【问题讨论】:

    标签: java android push-notification google-cloud-messaging


    【解决方案1】:

    以下是Sender.java 在sendNoRetry 方法中如何解析响应的示例:

       try {
          BufferedReader reader =
              new BufferedReader(new InputStreamReader(conn.getInputStream()));
          try {
            String line = reader.readLine();
    
            if (line == null || line.equals("")) {
              throw new IOException("Received empty response from GCM service.");
            }
            String[] responseParts = split(line);
            String token = responseParts[0];
            String value = responseParts[1];
            if (token.equals(TOKEN_MESSAGE_ID)) {
              Builder builder = new Result.Builder().messageId(value);
              // check for canonical registration id
              line = reader.readLine();
              if (line != null) {
                responseParts = split(line);
                token = responseParts[0];
                value = responseParts[1];
                if (token.equals(TOKEN_CANONICAL_REG_ID)) {
                  builder.canonicalRegistrationId(value);
                } else {
                  logger.warning("Received invalid second line from GCM: " + line);
                }
              }
    
              Result result = builder.build();
              if (logger.isLoggable(Level.FINE)) {
                logger.fine("Message created succesfully (" + result + ")");
              }
              return result;
            } else if (token.equals(TOKEN_ERROR)) {
              return new Result.Builder().errorCode(value).build();
            } else {
              throw new IOException("Received invalid response from GCM: " + line);
            }
          } finally {
            reader.close();
          }
        } finally {
          conn.disconnect();
        }
    

    如您所见,规范注册 ID 会在响应的第二行中搜索,但前提是响应的第一行包含消息 ID。

    【讨论】:

    • 对不起。我不明白。我必须在代码的哪一部分粘贴您的代码?
    • @Ton 您无法按原样复制它,因为您使用不同的类来处理来自 Google 的响应。这只是一个例子。你得到的回复是respData String。您必须检查它是否包含两行,如果包含,请检查第二行是否以registration_id开头。
    • 我明白了...我会检查的。谢谢
    【解决方案2】:

    推送通知后返回的结果中获取Canonical Id。

    假设消息已经构建并且您拥有设备的registrationId,下面是从我的服务器向单个设备发送GCM消息并从响应中获取规范ID的方法:-

    private void sendNotificationToSingleDevice(Message message, String registrationId) {
    
        try {
            //Send a message to a single device 
            Result result = sender.send(message, regtoken, 1);
            String canonicalId = result.getCanonicalRegistrationId();
            // do code to replace existing registration id with the canonical id
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    以下是从我的服务器广播消息并从响应中获取规范 id 的方法:-

    private void sendNotificationToMultipleDevices(Message message, List<String> registrationIds) {
    
        try {
            //Send a message to a multiple devices
            MulticastResult result = sender.send(message, registrationIds, 1);
            if (result.getResults() != null) {
                // this for loop loops through the response returned after pushing the message to each device.
                for(int i = 0; i < result.getResults().size(); i++) {
                   String canonicalId = result.getResults().get(i).getCanonicalRegistrationId(); 
                   // do code to replace existing registration id with the canonical id
                }
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2017-10-26
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多