Android使用Canonical ID GCM
问题描述:
正如我在这里指的 Android GCM messages repeated 问题是我安装并重新安装应用很多次,所以它有很多regId
。我发现许多帖子建议使用Canonical ID。我读了很多帖子,但我不知道如何应用它。这里是我的代码regId
:Android使用Canonical ID GCM
public String getRegId(){
int noOfAttemptsAllowed = 3; // Number of Retries allowed
int noOfAttempts = 0; // Number of tries done
boolean stopFetching = false; // Flag to denote if it has to be retried or not
String regId = "";
while (!stopFetching)
{
noOfAttempts ++;
try {
regId = gcm.register(PROJECT_NUMBER);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
Thread.sleep(4000); // Set this timing based on trial.
try {
regId = gcm.register(PROJECT_NUMBER);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
/* try
{
// Get the registration ID
regId = gcm.register(PROJECT_NUMBER);
} catch (Exception e) {}*/
if (!regId.equals("") || noOfAttempts > noOfAttemptsAllowed)
{
// If registration ID obtained or No Of tries exceeded, stop fetching
stopFetching = true;
}
if (!regId.equals(""))
{
// If registration ID Obtained, save to shared preferences
SharedPrefrencesMethods.savePreferences(activity, "regid", regid);
}
}
return regId;
}
答
是的。您可以使用规范ID来帮助您更轻松地从错误中恢复。它是客户端应用程序请求的最后一次注册的注册令牌。这是服务器在向设备发送消息时应使用的ID。
如果您尝试使用旧的注册令牌发送消息,GCM将像往常一样处理该请求,但它将在响应的
registration_id field
中包含规范ID。确保使用此规范ID替换存储在服务器中的注册令牌,因为最终旧注册令牌将停止工作。
根据此blog,GCM服务返回已发送订单通知中的cannonical ID。下面是一个示例响应:
{
"multicast_id": 7036866281258904189,
"success": 1,
"failure": 0,
"canonical_ids": 1,
"results": [
{
"registration_id": "CANNONICAL_REGISTRATION_ID",
"message_id": "0:1415529915241995%64ac3713f9fd7ecd"
}
]
}
的规范ID = 0意味着,用你的推服务器注册ID行,并且不应当通过典型ID代替,即经常GCM服务器将响应canonical_id = 0 在示例响应中,有一个cannonical id,这意味着您的服务器必须用您看到的新值替换现有的注册id。如果用户重新安装客户端应用程序,这种情况很容易重现,但您的推送服务器不知道它,并且GCM服务器将响应新的注册ID。
检查这些相关SO有关规范标识的问题:
好吧,谢谢你,我现在明白了,但我有个小问题,我不知道哪里来接收服务器回应在哪个方法我的意思是我有onHandleIntent意图方法我试图只能得到消息本身? – Radwa
你好我mange从服务器得到的回应,并获得规范的ID,但我发现了许多规范ID我应该使用这是JSON响应的一部分 {“success”:17,“failure”:15,“canonical_ids”:16 } – Radwa