2014-07-04 22 views
0

我是GCM的新手,我不知道如何从响应中获取Cannonical Id。这是我读的:CM获取Canonical 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?

由于

回答

0

以下是如何响应由Sender.javasendNoRetry方法解析了一个例子:

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。

+0

对不起。我不明白。在我的代码的哪一部分,我必须粘贴你的代码? – Ton

+0

@Ton您无法复制它,因为您正在使用不同的类来处理来自Google的响应。这只是一个例子。你得到你的回应是'respData'字符串。你必须检查它是否包含两行,如果是,请检查第二行是否以registration_id开头。 – Eran

+0

我明白了...我会检查它。谢谢 – Ton

0

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(); 
    } 
} 

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

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(); 
    } 
}