title: Firebase initialization fails for Android on Xamarin.Forms app
body: <p>I'm following the tutorial <a href="https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm" rel="nofollow noreferrer">here</a> to set up Firebase Cloud Messaging for Android in my Xamarin.Forms application. This is an app that currently uses Google Cloud Messaging (GCM). I believe I followed all of the steps in the tutorial. However, my <code>OnTokenRefresh</code> method or <code>OnMessageReceived</code> method never fires.</p>
  
  <p>In my Droid project, I have the packages Xamarin.Firebase.Common, Xamarin.Firebase.Iid, Xamarin.Firebase.Messaging, Xamarin.GooglePlayServices.Base, Xamarin.GooglePlayServices.Basement, Xamarin.GooglePlayServices.Tasks. I also have about 70 other packages (I didn't create this app). I removed any packages related to GCM, and removed GCM-related code. My google-services.json is set to GoogleServicesJson build action. </p>
  
  <p>When I tried adding <code>Console.Out.WriteLine("MainActivity InstanceID token: " + FirebaseInstanceId.Instance.Token);</code> to MainActivity's <code>OnCreate</code> method to try to force the app to give me a token, it crashes with the error:</p>
  
  <pre><code>Java.Lang.IllegalStateException
  
  Default FirebaseApp is not initialized in this process com.ebelinski.fakename. Make sure to call FirebaseApp.initializeApp(Context) first.
  </code></pre>
  
  <p>I've tried a bunch of different things and nothing seems to work. Below is my code:</p>
  
  <p><strong>WinterFirebaseIIDService.cs</strong></p>
  
  <pre><code>using System.Collections.Generic;
  using Android.App;
  using WindowsAzure.Messaging;
  using Firebase.Iid;
  
  namespace FakeName.Droid {
  
    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class WinterFirebaseIIDService: FirebaseInstanceIdService {
  
      NotificationHub hub;
  
      public override void OnTokenRefresh() {
        var refreshedToken = FirebaseInstanceId.Instance.Token;
        AppLog.Checkpoint("WinterFirebaseIIDService FCM token: " + refreshedToken);
        SendRegistrationToServer(refreshedToken);
      }
  
      void SendRegistrationToServer(string token) {
        // Register with Notification Hubs
        hub = new NotificationHub(AppConstants.NOTIFICATION_HUB_NAME,
                                  AppConstants.NOTIFICATION_HUB_CONNECTION, this);
  
        var tags = new List&lt;string&gt;() { };
        var regID = hub.Register(token, tags.ToArray()).RegistrationId;
  
        AppLog.Checkpoint("WinterFirebaseIIDService Successful registration of ID " + regID);
      }
  
    }
  
  }
  </code></pre>
  
  <p><strong>WinterFirebaseMessagingService</strong></p>
  
  <pre><code>using System.Linq;
  using Android.App;
  using Firebase.Messaging;
  
  namespace FakeName.Droid {
  
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class WinterFirebaseMessagingService: FirebaseMessagingService {
  
      public override void OnMessageReceived(RemoteMessage message) {
        AppLog.Checkpoint("WinterFirebaseMessagingService From: " + message.From);
        if (message.GetNotification() != null) {
          //These is how most messages will be received
          AppLog.Checkpoint("WinterFirebaseMessagingService Notification Message Body: " + message.GetNotification().Body);
          SendNotification(message.GetNotification().Body);
        }
        else {
          //Only used for debugging payloads sent from the Azure portal
          SendNotification(message.Data.Values.First());
  
        }
  
      }
  
      void SendNotification(string messageBody) {
      }
  
    }
  
  }
  </code></pre>
  
  <p><strong>AndroidManifest.xml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ebelinski.fakename" android:versionName="1.1" android:versionCode="15"&gt;
      &lt;uses-sdk android:minSdkVersion="15" android:targetSdkVersion="28" /&gt;
      &lt;application android:label="Fake Name"&gt;
          &lt;receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" /&gt;
          &lt;receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND"&gt;
              &lt;intent-filter&gt;
                  &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
                  &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt;
                  &lt;category android:name="${applicationId}" /&gt;
              &lt;/intent-filter&gt;
          &lt;/receiver&gt;
      &lt;/application&gt;
      &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
      &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt;
  &lt;/manifest&gt;
  </code></pre>
  
  <p><strong>AndroidMaifest.xml (the version in /Droid/obj/Debug/android/)</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ebelinski.fakename" android:versionName="1.1" android:versionCode="15"&gt;
    &lt;uses-sdk android:minSdkVersion="15" android:targetSdkVersion="28" /&gt;
    &lt;permission android:name="com.ebelinski.fakename.permission.C2D_MESSAGE" /&gt;
    &lt;uses-permission android:name="com.ebelinski.fakename.permission.C2D_MESSAGE" /&gt;
    &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
    &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
    &lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt;
    &lt;uses-feature android:name="android.hardware.location.gps" /&gt;
    &lt;uses-feature android:name="android.hardware.location.network" /&gt;
    &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
    &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
    &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;
    &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt;
    &lt;application android:label="Fake Name" android:name="android.support.multidex.MultiDexApplication" android:allowBackup="true" android:icon="@drawable/icon" android:debuggable="true"&gt;
      &lt;receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" /&gt;
      &lt;receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
          &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt;
          &lt;category android:name="com.ebelinski.fakename" /&gt;
        &lt;/intent-filter&gt;
      &lt;/receiver&gt;
      &lt;activity android:configChanges="orientation|screenSize" android:icon="@drawable/icon" android:label="Fake Name" android:launchMode="singleTop" android:theme="@style/CustomTheme" android:name="md501b8064acb9363ced7fe7144b683c1bc.MainActivity"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="android.intent.action.MAIN" /&gt;
          &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
        &lt;/intent-filter&gt;
      &lt;/activity&gt;
      &lt;activity android:configChanges="orientation|screenSize" android:label="Notification Activity" android:name="md501b8064acb9363ced7fe7144b683c1bc.NotificationActivity" /&gt;
      &lt;service android:name="md501b8064acb9363ced7fe7144b683c1bc.BackgroundService"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="FakeName.Droid.BackgroundService" /&gt;
        &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;service android:name="md501b8064acb9363ced7fe7144b683c1bc.WinterFirebaseIIDService"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="com.google.firebase.INSTANCE_ID_EVENT" /&gt;
        &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;service android:name="md501b8064acb9363ced7fe7144b683c1bc.WinterFirebaseMessagingService"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="com.google.firebase.MESSAGING_EVENT" /&gt;
        &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;receiver android:enabled="true" android:exported="false" android:name="md51558244f76c53b6aeda52c8a337f2c37.PowerSaveModeBroadcastReceiver" /&gt;
      &lt;provider android:name="mono.MonoRuntimeProvider" android:exported="false" android:initOrder="2147483647" android:authorities="com.ebelinski.fakename.mono.MonoRuntimeProvider.__mono_init__" /&gt;
      &lt;!--suppress ExportedReceiver--&gt;
      &lt;receiver android:name="mono.android.Seppuku"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="mono.android.intent.action.SEPPUKU" /&gt;
          &lt;category android:name="mono.android.intent.category.SEPPUKU.com.ebelinski.fakename" /&gt;
        &lt;/intent-filter&gt;
      &lt;/receiver&gt;
      &lt;provider android:authorities="com.ebelinski.fakename.firebaseinitprovider" android:name="com.google.firebase.provider.FirebaseInitProvider" android:exported="false" android:initOrder="100" /&gt;
      &lt;receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND"&gt;
        &lt;intent-filter&gt;
          &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
          &lt;category android:name="com.ebelinski.fakename" /&gt;
        &lt;/intent-filter&gt;
      &lt;/receiver&gt;
      &lt;!-- Internal (not exported) receiver used by the app to start its own exported services
               without risk of being spoofed. --&gt;
      &lt;!-- FirebaseInstanceIdService performs security checks at runtime,
               no need for explicit permissions despite exported="true" --&gt;
      &lt;service android:name="com.google.firebase.iid.FirebaseInstanceIdService" android:exported="true"&gt;
        &lt;intent-filter android:priority="-500"&gt;
          &lt;action android:name="com.google.firebase.INSTANCE_ID_EVENT" /&gt;
        &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;!-- FirebaseMessagingService performs security checks at runtime,
               no need for explicit permissions despite exported="true" --&gt;
      &lt;service android:name="com.google.firebase.messaging.FirebaseMessagingService" android:exported="true"&gt;
        &lt;intent-filter android:priority="-500"&gt;
          &lt;action android:name="com.google.firebase.MESSAGING_EVENT" /&gt;
        &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;activity android:name="com.google.android.gms.common.api.GoogleApiActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:exported="false" /&gt;
      &lt;meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /&gt;
    &lt;/application&gt;
    &lt;permission android:name="com.ebelinski.fakename.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt;
    &lt;uses-permission android:name="com.ebelinski.fakename.permission.C2D_MESSAGE" /&gt;
  &lt;/manifest&gt;
  </code></pre>
  
  <p><strong>MainActivity.cs</strong></p>
  
  <pre><code>using Android.App;
  using Android.Content.PM;
  using Android.OS;
  using System.Globalization;
  using Xamarin;
  using FakeName.Infrastructure;
  using FakeNameDroid.Infrastructure;
  using Android.Content;
  using System;
  using FakeNameMessaging;
  using FakeNameModels;
  using Firebase.Iid;
  using Firebase.Messaging;
  using Firebase;
  
  namespace FakeName.Droid
  {
    [Activity (Label = "FakeName", LaunchMode = LaunchMode.SingleTop, Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, Theme = "@style/CustomTheme")]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
  
      // This will be set to true in the OnNewIntent method to notify the app should navigate to the notifications page after launching
      private bool navigateToNotifications = false;
  
      // Google API Project Number
      public static MainActivity instance;
  
      protected override void OnCreate (Bundle bundle)
      {
        AppLog.Checkpoint("MainActivity OnCreate");
  
        instance = this;
        base.OnCreate (bundle);
  
        AppLog.Checkpoint("MainActivity Initializing Xamarin Forms");
        global::Xamarin.Forms.Forms.Init (this, bundle);
  
        // Set up the Translation service based on the current culture
        Translate.Initialize (CultureInfo.CurrentCulture.TwoLetterISOLanguageName);
  
        SettingsPageModel.ShowManageNotificationsButton = true;
  
  
        try
        {
          string notificationData = null;
          if(bundle != null) {
            notificationData = bundle.GetString("notification");
          } else {
            notificationData = Intent.GetStringExtra("notification");
          }
  
          if (!string.IsNullOrEmpty(notificationData)) {
            AppLog.Checkpoint("MainActivity Notification Data Present in bundle");
            navigateToNotifications = true;
          } else {
            AppLog.Checkpoint("MainActivity Notification Data not present in bundle");
          }
        }
        catch (Exception ex)
        {
          AppLog.Checkpoint("MainActivity Exception getting notification data OnCreate");
          AppLog.CaptureException ("MainActivity CheckForNotificationData", ex);
        }
  
        FillIoCContainer();
        CreateNotificationChannel();
  
        if (navigateToNotifications) {
          LoadApplication (new App (NavigationDetailPage.Notifications));
          // Reset flag
          navigateToNotifications = false;
        } else {
          LoadApplication (new App ());
        }
  
        // NOTE: I added this even though it didn't say so in the tutorial...it doesn't work with or without it...
        FirebaseApp app = FirebaseApp.InitializeApp(Android.App.Application.Context);
      }
  
      protected override void OnResume ()
      {
        base.OnResume();
  
        AppLog.Checkpoint("MainActivity OnResume");
  
        // NOTE: This is where the app crashes. It crashes even if I move this line to OnCreate.
        Console.Out.WriteLine("MainActivity InstanceID token: " + FirebaseInstanceId.Instance.Token);
  
        if (navigateToNotifications) {
          AppLog.Checkpoint("MainActivity Navigating to notifications");
          GalaSoft.MvvmLight.Messaging.Messenger.Default.Send (new NavigationMessageEvent (NavigationDetailPage.Notifications));
          navigateToNotifications = false; // reset the value
        }
      }
  
      /* 
       * The intent that calls MainActivity from a notification is actually a different intent than the one we built and won't 
       * have the extra data we put in it. This method 'OnNewIntent' catches our intent that was tied to that notification so
       * we can get the extra data we put in it when the user click it.
       */
      protected override void OnNewIntent(Intent intent)
      {
        base.OnNewIntent(intent);
        AppLog.Checkpoint("MainActivity OnNewIntent called");
  
        try
        {
          var notificationData = intent.GetStringExtra("notification");
          if (!string.IsNullOrEmpty(notificationData)) {
            AppLog.Checkpoint("MainActivity Notification Data Present");
            navigateToNotifications = true;
          }
        }
        catch (Exception ex)
        {
          AppLog.Checkpoint("MainActivity Exception getting notification ");
          AppLog.CaptureException ("CheckForNotificationData", ex);
        }
      }
  
      private void CreateNotificationChannel() {
        if (Build.VERSION.SdkInt &gt;= BuildVersionCodes.O) {
          string name = "Snow emergency notifications";
          string description = "This notification channel contains snow emergency notifications.";
          NotificationImportance importance = NotificationImportance.Max;
          string channelID = AppConstants.NOTIFICATION_CHANNEL_SNOW_EMERGENCIES_ID;
  
          NotificationChannel channel = new NotificationChannel(channelID, name, importance);
          channel.Description = description;
  
          NotificationManager notificationManager = (NotificationManager) GetSystemService(NotificationService);
          notificationManager.CreateNotificationChannel(channel);
        }
      }
  
      public void FillIoCContainer ()
      {
        AppLog.Checkpoint("MainActivity Filling IoC");
        IoCContainer.Instance.AddInstance&lt;INetworkConnectionMonitor&gt; (new NetworkConnectionMonitor ());
      }
    }
  }
  </code></pre>