在GCM:入门指南的最后一节中,接收结果后需要进行一些记录工作。
引用指南中的内容:
现在需要解析结果并在以下情况下采取适当的操作:
- 如果消息已创建但结果返回一个规范化的注册ID,则需要使用规范化的注册ID替换当前注册ID。
- 如果返回的错误是NotRegistered,则需要删除该注册ID,因为应用程序已从设备中卸载。
这里是处理这两种情况的代码片段:
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
}
}
上面的指南只针对单个结果,不适用于多播情况。我不确定如何处理多播情况: ArrayList<String> devices = new ArrayList<String>();
for (String d : relevantDevices) {
devices.add(d);
}
Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().addData("hello", "world").build();
try {
MulticastResult result = sender.send(message, devices, 5);
for (Result r : result.getResults()) {
if (r.getMessageId() != null) {
String canonicalRegId = r.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
// BUT WHICH DEVICE IS IT?
}
} else {
String error = r.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
// BUT WHICH DEVICE IS IT?
}
}
}
} catch (IOException ex) {
Log.err(TAG, "sending message failed", ex);
}
我提交了一个设备列表,并收到了结果列表。
结果对象不包含注册ID,只包含第一个ID过时时的规范化ID。
未说明这两个列表是否相关(例如,是否保留顺序和大小)。我如何确定哪个结果与哪个设备相关?
-- 更新
我在下面单独的答案中粘贴了解决方案的片段。