title: How to keep GCM in sync with app and server?
body: <p>I am using GCM for app notifications as illustrated <a href="http://developer.android.com/google/gcm/gs.html" rel="nofollow">here</a>.  The code is boilerplate:</p>
  
  <pre><code>GCMRegistrar.checkDevice(this);
  GCMRegistrar.checkManifest(this);
  
  final String regId = GCMRegistrar.getRegistrationId(this);
  if (regId.equals("")) {
      GCMRegistrar.register(this, SENDER_ID);
  } else {
      Log.v(TAG, "Already registered");
  }
  </code></pre>
  
  <p>Then the <code>onRegistered()</code> callback updates my server with the returned registration id.</p>
  
  <p>However, on several occasions GCM has gotten into an inconsistent state.  In one case, it doesn't forward any notifications even though <code>GCMRegistrar.getRegistrationId()</code> gives me a non-empty registration id string.  In other cases, I end up getting two or more duplicate messages.</p>
  
  <p>In attempt to avoid these situations, I currently have a brute force solution that works like this:</p>
  
  <pre><code>if (GCMRegistrar.isRegistered(this))
      GCMRegistrar.unregister(this);
  else
      GCMRegistrar.register(this, GCMConstants.SENDER_ID);
  </code></pre>
  
  <p>In the onUnregistered() callback, I tell my server to delete the registration id, and then call <code>GCMRegistrar.register()</code>.  In the <code>onRegistered()</code> callback, I tell my server to add the registration id back.</p>
  
  <p>So far, it's working, but it's obviously less efficient than the way this is supposed to work, and I don't know for sure if it's immune to the inconsistency problems.  It would be better if I could count on <code>getRegistrationId()</code> to always return a valid id, i.e., the current/canonical registration id.</p>
  
  <p><strong>What's the simplest/cleanest way to ensure consistency between my app, my server, and GCM?</strong>  Thanks.</p>