android GCM get original id of canonical id

2019-01-14 13:57发布

问题:

I am trying to send a push update to some android devices. Some of them have got a new id in the mean time, so I Google tells me there are canonical ids. From the documentation I read:

If message_id is set, check for registration_id:

  • If registration_id is set, replace the original ID with the new value (canonical ID) in your server database. Note that the original ID is not part of the result, so you need to obtain it from the list of registration_ids passed in the request (using the same index).

Am I missing a part, or is this ambiguous if you send more than 1 registration id to Google?

My request (replaced ids for readability):

"{"data":{"favorite":1},"registration_ids":["1","2","3","4","5","6"]}"

The response from Google is:

{
  "multicast_id":7917175795873320166,
  "success":6,
  "failure":0,
  "canonical_ids":4,
  "results":[
    {"registration_id":"3","message_id":"m1"},
    {"message_id":"m1"},
    {"message_id":"m1"},
    {"registration_id":"3","message_id":"m1"},
    {"registration_id":"3","message_id":"m1"},
    {"registration_id":"3","message_id":"m1"}
 ]
}

From this, I know that id 3 is correct, but which original ids should I replace with 3? Sending every message for every registered id would be a waste. I have read a post here on Stackoverflow ( GCM and id handling ) solving it for a Java server, but mine is not (RoR).

Any ideas on how to solve this issue?

回答1:

As described in the post that you linked to, it's all based on the position in the response list. So when you get the canonical ID you need to update the original registration ID in the same position of your "send list".

So in your example here are the results 4 of which are canonical (0, 3, 4, 5):

[0] {"registration_id":"3","message_id":"m1"},
[1] {"message_id":"m1"},
[2] {"message_id":"m1"},
[3] {"registration_id":"3","message_id":"m1"},
[4] {"registration_id":"3","message_id":"m1"},
[5] {"registration_id":"3","message_id":"m1"}

And here is your "send list":

[0] "1",
[1] "2",
[2] "3",
[3] "4",
[4] "5",
[5] "6"

According to the results you need to update the registration ID's in position 0, 3, 4, 5 to the ID of 3. That means that you will end up with a registration list like the following:

[0] "3",
[1] "2",
[2] "3",
[3] "3",
[4] "3",
[5] "3"

And finally:

[0] "3",
[1] "2",

Also see: https://developer.android.com/google/gcm/adv.html#canonical and https://developer.android.com/google/gcm/gcm.html#response