我正在给出一种方法,就像我在应用程序中实现的一样
@Overrideprotected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); //displayMessage(context, getString(R.string.gcm_registered)); //ServerUtilities.register(context, registrationId); //1. Store this id to application Prefs on each request of device registration //2. Clear this id from app prefs on each request of device un-registration //3. Now add an if check for new registartion id to server, you can write a method on server side to check if this reg-id matching for this device or not (and you need an unique identification of device to be stored on server) //4. That method will clear that if id is matching it meanse this is existing reg-id, and if not matching this is updated reg-id. //5. If this is updated reg-id, update on server and update into application prefs.}你也可以这样
if reg_id exists_into prefrences then if stored_id equals_to new_reg_id then do nothing else say server to reg_id updated update prefrences with new id end ifelse update this id to application prefs say server that your device is registeredend if
但是,当用户清除应用程序数据并且您将丢失当前的注册表ID时,就会出现问题。
新API示例示例的更新
功劳归功于Eran及其Android上的Google
Cloud Messaging中的)他的答案处理注册ID更改
Google更改了其演示应用程序以使用新界面。他们通过在应用程序本地保留的值上设置过期日期来刷新注册ID。应用启动时,他们会加载其本地存储的注册ID。如果它已“过期”(在演示中这意味着它是7天前从GCM收到的),他们会
gcm.register(senderID)再次致电。
这不适用于假设的情况,在这种情况下,Google会为长时间未启动的应用刷新注册ID。在这种情况下,应用程序将不会知道更改,第三方服务器也不会。
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); context = getApplicationContext(); regid = getRegistrationId(context); if (regid.length() == 0) { registerBackground(); } gcm = GoogleCloudMessaging.getInstance(this);}private String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.length() == 0) { Log.v(TAG, "Registration not found."); return ""; } // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion || isRegistrationExpired()) { Log.v(TAG, "App version changed or registration expired."); return ""; } return registrationId;}private boolean isRegistrationExpired() { final SharedPreferences prefs = getGCMPreferences(context); // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); return System.currentTimeMillis() > expirationTime;}


