获取已注册设备的GCM注册ID

时间:2014-04-03 12:02:33

标签: android push-notification session-cookies google-cloud-messaging

我在我的应用程序中使用GCM。它工作正常。我也将它存储在数据库中。

但是现在按照我的要求,我想要在以后注册设备的GCM注册ID。那有没有办法得到这个?我不想将其存储在CookiesSession中。

2 个答案:

答案 0 :(得分:1)

是的,以您喜欢的语言实现您的远程服务器(如此基础架构所需)并将其存储在某处:您的MySQL数据库,文件或任何您想要的内容。

恢复,您需要实现一个Web服务,该服务将存储任何已注册的GCM ID(例如,本地MySQL数据库),以便以后可以检索它。这样做,您还需要关注超时(例如,如果客户端在X时间内没有发送保持活动,只需将其从数据库中删除)。

答案 1 :(得分:1)

多次调用gcm.register(不调用gcm.unregister)将返回相同的注册ID。但是,没有理由这样做 - 它会导致您的应用程序与GCM服务器进行不必要的通信。

您可以将注册ID存储在应用的共享偏好设置中,如official GCM demo app所示:

/**
 * Stores the registration ID and the app versionCode in the application's
 * {@code SharedPreferences}.
 *
 * @param context application's context.
 * @param regId registration ID
 */
private void storeRegistrationId(Context context, String regId) {
    final SharedPreferences prefs = getGcmPreferences(context);
    int appVersion = getAppVersion(context);
    Log.i(TAG, "Saving regId on app version " + appVersion);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.commit();
}

只要您在应用中需要它,就可以从共享首选项中获取它(除非安装了新版本的应用,在这种情况下,Google建议使存储的注册ID无效并再次致电gcm.register):

/**
 * Gets the current registration ID for application on GCM service, if there is one.
 * <p>
 * If result is empty, the app needs to register.
 *
 * @return registration ID, or empty string if there is no existing
 *         registration ID.
 */
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;
}