Get GCM canonical registration ID without sending

2019-03-16 06:22发布

问题:

I have a problem with an app using GCM, the scenario is this:

  1. the app is installed
  2. the app calls the GCM register method getting the registration id "RID-1"
  3. the app is uninstalled
  4. the app is installed again
  5. the app calls the GCM register method again getting the registration id "RID-2"

In step 5, I need to get the previous registration id so I can update my model.

Limitations:
- I am trying to do this without using the external storage
- I can't update the model when the server sends a message, it should be done after the registration because a new profile is created in the app for each new device

I know that this information is in Google servers because it is sent to you when you send a message to the old registration id. For example, if I send a message to "RID-1", in the response I get that the new (canonical) registration id is "RID-2". What I need is a way to get this information without sending a message.

Let me know if you need more context.


I found several related questions but the answers doesn't apply to this scenario:
Registration ID duplication for GCM
gcm canonical id should be updated or not
Persistance of gcm registration id
Google Cloud Messaging - Registration ID status
Android GCM: How to detect registered canonical ids in my own server?
Handling registration ID changes in Google Cloud Messaging on Android
(all answered by @eran)

回答1:

You can specify "dry_run": true option in /send request.

I found that devices do not receive any push notifications with "dry_run": true option, while a server get canonical_ids response.

Here is a sample code in Ruby. You may have to install gcm Gem beforehand.

$ gem install gcm

ask_canonical_ids.rb

require 'gcm'
require 'json'

API_KEY = "YourApiKey"
gcm = GCM.new(API_KEY)

registration_ids = [
  'OldRegistrationId',
]

option = { data: { 'message' => 'Hello Gcm!' }, dry_run: true }
response = gcm.send_notification(registration_ids, option)

p response[:canonical_ids]

output of $ ruby ask_canonical_ids.rb (formatted)

[{
  :old => "OldRegistrationId",
  :new => "NewRegistrationId"
}]

Again, your device will not receive any push notifications.



回答2:

We need to update registration id with Canonical Id( By finding index position of array). You may Follow this working Ready use Code



回答3:

If all you need is that the user should not get a notification, send a message with parameters that your application is not looking for. You will get the canonical and your app will discard the notification if it does not have the mandatory text and message.

For example, my Cordova application plugin requires the key 'message' in the data received from the server. Otherwise it does not create a notification.

I know this is sort of a hack, but I think given the limitations, this will be the easiest to achieve.