我知道这个问题已经被问过几次了,但我还没有找到满意的答案,因为 Google 的 GCM 教程中的一部分文字让我感到厌烦:
A given regID is not guaranteed to last indefinitely, so the first thing your app should always do is check to make sure it has a valid regID (as shown in the code snippets above)
我将返回的 ID 和应用程序版本保存在设备上的表中,每次在启动器 Activity 应用程序中检查 ID 并注册设备(如果 ID 不存在)。
但是,“regID 不能保证无限期地持续”是什么意思?如果设备仅在共享首选项或表中在本地检查它,如何知道它是否在 GCM 服务器上丢失了其 regID?
最佳答案
正在经历code ,看来 Google 只希望我们在应用程序更新时重新注册。
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
GCMRegistrar.getRegistrationId也做同样的事情。现在是deprecated .
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
Log.v(TAG, "App version changed from " + oldVersion + " to " +
newVersion + "; resetting registration id");
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
编辑
浏览文档和代码(至少)我找不到任何其他方式让客户知道是否需要重新注册。但是,当您尝试向过期或重复的注册 ID 发送通知时,您可能会收到一些服务器错误响应。如果注册 ID 已过期,应用服务器可以要求客户端重新注册,如果是 duplicate应用服务器应将现有的注册 ID 替换为 Google 返回的 canonical_id。
请阅读此link有关如何解释这些错误消息的更多详细信息。
希望这有帮助。
关于android - 如何检查设备是否已注册 GCM,因为官方教程指出 "regID is not guaranteed to last indefinitely",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057925/