android - 如何检查设备是否已注册 GCM,因为官方教程指出 "regID is not guaranteed to last indefinitely"

标签 android google-cloud-messaging

我知道这个问题已经被问过几次了,但我还没有找到满意的答案,因为 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/

相关文章:

android - 具有 Material 设计的自定义搜索栏

android - 位置管理器 requestLocationUpdates 只调用一次

android - 为什么我从 GCM 服务器端得到 "MismatchSenderId"?

jakarta-ee - 如何验证android设备 token

php - 如何使用 ip 指定端口号以注册 gcm 服务器

android - 捕获推送通知android

Android 架构组件 : Get Activity methods when using LifecycleOwner

android - System.out resolveUri 在错误的位图 uri : https://. 上失败 .. 当我尝试将图片从 Web 插入到 ListView 时

Facebook - android 应用程序没有互联网通知 ui 元素

Android 解析、通知和构建类型