1

I created a Push Notification Server (PNS) by using Google Cloud Messaging (GCM). With this architecture, my server has to know the token associated to a user in order to send him push notifications.

I extended the class InstanceIDListenerService which is correctly notified when a token has been refreshed (I tested it with adb). When its method onTokenRefresh() is called I take the new token and, so far, all is ok.

My problem is the following: what if I fail to send this new token to my server? (a network error, a lack of connection, a sudden device shutdown, or something else...). Do I have to store somewhere (preferences?) that server does not know my new token and retry when possible? Is there a way to let the OS to perform this operation?

Massimo
  • 3,436
  • 4
  • 40
  • 68
  • 3
    _"Do I have to store somewhere (preferences?) that server does not know my new token and retry when possible?"_ The [gcmquickstart sample app](https://github.com/googlesamples/google-services/tree/master/android/gcm/app/src/main/java/gcm/play/android/samples/com/gcmquickstart) does just that, so you could take a look at their implementation. – Michael Nov 06 '15 at 17:31
  • Ok, the idea is not bad. But there is a problem: my app may not be running when I am notified that the token has to be refreshed, then if I fail that only opportunity to send the token to my server I will lose all the (eventual) notifications in the time between the onTokenRefresh call and the next start of my app. (maybe I am magnifying the problem more than necessary) – Massimo Nov 06 '15 at 17:40

2 Answers2

0

Your app (when it runs) should always check if the token has been sent to the server. When onTokenRefresh is called you should generate and send a new token to the server. If sending the token to the server fails then the next time your app runs it should try again.

You are correct that if you fail to send the token to the server onTokenRefresh your app will not receive notifications till it is run again and successfully sends the token to the server.

Also note that token refresh should not be a regular occurrence. It should only happen for example when the app is uninstalled and reinstalled or the token is deemed to be no longer secure.

Arthur Thompson
  • 9,087
  • 4
  • 29
  • 33
0

You may use GCM NetworkManager to queue, schedule, check network connections and... , its very reliable and useful, it handles all of your desired tasks.

Also you have to save your token some where is your device, may be on your shared preferences, till you make sure your server recives it. Please note that if you want to use other features of GCM like topic messaging, you have to save and use token for all topic registrations.

Ali
  • 539
  • 4
  • 18