rotorgames / Rg.Plugins.Popup

Xamarin Forms popup plugin
MIT License
1.15k stars 337 forks source link

Using this plugin with Firebase Cloud Messaging notifications #641

Open JesperNJessen opened 3 years ago

JesperNJessen commented 3 years ago

💬 Questions and Help

For anyone who might have the same issues I had today. When using this plugin in conjunction with Firebase Cloud Messaging for notifications, you will most likely get an InvalidCastException when trying to push a popup page to the PopupNavigation stack on Android.

This is because the plugin has not been initialized correctly. I had this in my MainActivity/OnCreate:

protected override void OnCreate(Bundle savedInstanceState)
{
      (...)

      base.OnCreate(savedInstanceState);

      (...)

      global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
      Rg.Plugins.Popup.Popup.Init(Application.Context);
      Firebase.FirebaseApp.InitializeApp(Application.Context);

      LoadApplication(new App());

      (...)
}

Which would seem fine, but the line

Firebase.FirebaseApp.InitializeApp(Application.Context);

which is needed for Firebase Cloud Messaging, changes the Context of the Application. To fix this, I used CrossCurrentActivity and initialized it on the Application level:

Add a new C# class file in your project called "MainApplication.cs".
Override the OnCreate method and call the Init method
#if DEBUG
[Application(Debuggable = true)]
#else
[Application(Debuggable = false)]
#endif
public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer)
        : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();
        CrossCurrentActivity.Current.Init(this);
    }
}
If you already have an "Application" class in your project simply add the Init call.

In my MainActivity/OnCreate I changed my code to this:

protected override void OnCreate(Bundle savedInstanceState)
{
      (...)

      base.OnCreate(savedInstanceState);

      (...)

      global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
--> Rg.Plugins.Popup.Popup.Init(CrossCurrentActivity.Current.Activity); <-- 
      Firebase.FirebaseApp.InitializeApp(Application.Context);

      global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
      LoadApplication(new App());

      (...)
}

I am now able to use this plugin just like before I added notifications from Firebase Cloud Messaging

LuckyDucko commented 3 years ago

@JesperNJessen

Do you want to create a Wiki Page out of this issue, and ill add it as a section along in our wiki? seems like a handy bit of advice