title: Xamarin Android Firebase refresh token
body: <p>I implemented Firebase messaging into our Xamarin Android app. The very first time the app was run it called OnTokenRefresh() as excepted. I uninstalled the app and re-ran the debugger which reinstalled the app. This time though, OnTokenRefresh was not called. In fact, I haven't been able to get it to be called a second time for a single device.</p>
  
  <p>I tried making a token service to get the token but it always throws an exception. The method is very simple:</p>
  
  <pre><code> [assembly: 
   Xamarin.Forms.Dependency(typeof(MyApp.Droid.Services.NotificationToken))]
    namespace MyApp.Droid.Services
   {
   class NotificationToken : INotificationToken
   {
      public string GetToken()
      {            
          var token = "";
          if (Firebase.Iid.FirebaseInstanceId.Instance != null)
              token = Firebase.Iid.FirebaseInstanceId.Instance.Token;
          return token;
       }
     }
  }
  </code></pre>
  
  <p>The exception is thrown on the check if Instance is null.</p>
  
  <pre><code> [GoogleAccountDataServiceImpl] getToken() -&gt; BAD_AUTHENTICATION. Account: &lt;ELLIDED:-119322310&gt;, App: com.google.android.gms, Service: oauth2:https://www.googleapis.com/auth/gcm
  </code></pre>
  
  <p>I'm calling the service well after the main activity has been created. It's called after the user logs into our app.</p>
  
  <p>I have the google-services.json included in our Android project. I'm pretty certain it's being used since the initial time the app was installed it created the token and called OnTokenRefresh.</p>
  
  <pre><code>     [Service]
  [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
  public class MyFirebaseIIDService : FirebaseInstanceIdService
  {
      const string TAG = "MyFirebaseIIDService";
  
      public override void OnCreate()
      {
          base.OnCreate();
          //FirebaseInstanceId.Instance.GetToken();
      }
      public override void OnTokenRefresh()
      {
          var refreshedToken = FirebaseInstanceId.Instance.Token;
          App.NotificationToken.Token = refreshedToken;
          Log.Debug(TAG, "Refreshed token: " + refreshedToken);
      }        
  }
  </code></pre>