Tal*_*nel 5 android push-notification google-cloud-messaging
这是许多应用程序面临的常见情况,但我正在分散理解如何实现:
假设我的应用程序是一个具有当前登录用户的社交网络.我想向当前用户登录的所有设备发送GCM消息给该用户.
这意味着我的服务器为每个用户保存了他所有注册ID的列表 - 每个用户的一个注册ID.
问题:如何唯一地跟踪他的每个设备? 似乎没有可靠的方法来获取特定的设备标识符
没有为每个独特的设备存储注册ID - 我不知道如何管理它.
当用户将卸载/注销并随后获得新的注册ID时,事情变得混乱,假设要替换现有的已知id之一,但是哪一个?
如果我喜欢只向特定设备发送消息,而不是所有设备,那么事情会变得更加棘手......
请帮助我理解我遗漏的内容,以及为同一用户处理多个设备注册ID的正确方法.
在使用GCM时,Google会为您处理所有艰苦的工作.他们提供了一种简单的方法来始终保持注册ID的最新状态.每个被发送的消息都有一个额外的字段canonicalRegistrationId.如果该字段中有id,则注册ID已更改并需要更新.每个消息都存在此字段,每次发送一个消息时,都必须检查该字段.如果有新的,canonicalRegistrationId那么你应该尽快更新registrationId.旧的可能会继续工作一段时间,但没有告诉它何时变得无效.
例如,在Google App Engine后端,处理更改注册ID的代码将如下所示:
// We want to send a message to some devices
// Get registered devices and then loop through them
List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list();
for(RegistrationRecord record : records) {
// Send the message to one device
Result result = sender.send(msg, record.getRegId(), 5);
// If the messageId is not null, then the message has been sent successfully
if (result.getMessageId() != null) {
log.info("Message sent to " + record.getRegId());
// Check for canonical message id
// If it is not null, then the registrationId has changed
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// The registrationId has changed! We need to update it in the database
log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId);
record.setRegId(canonicalRegId);
ofy().save().entity(record).now();
}
} else {
... // Irrelevant error handling
}
}
Run Code Online (Sandbox Code Playgroud)
所以你要做的就是非常简单:每次发送消息时,检查是否有消息,如果是canonicalRegistrationId,则用规范更新旧的registrationId.
| 归档时间: |
|
| 查看次数: |
4173 次 |
| 最近记录: |