Reference to MainActivity from another class

I am using DependencyService to perform a Facebook login in each platform.
In my android implementation class I use the I use the Xamarin.Facebook. So the login is performed through:

LoginManager.Instance.LogInWithReadPermissions(this, new List { "public_profile", "user_friends" });

Where (this) is an argument of class Android.App.Activity and it should reference to the Active/Current Activity.

If I replace it with MainActivity it will not run because MainActivity is a class not an instance

How to reference The MainActivity/Current Activity from another class?

Thank you for help.

Best Answer


  • OussamaAlRifaiOussamaAlRifai AEMember

    @AdamP thank you for response. It is definitely useful.
    But for my solution it was enough to use:
    Xamarin.Forms.Forms.Context as MainActivity

  • RayGoudieRayGoudie CAMember ✭✭

    Your solution is obsolete as of version 2.5. Are there any updated solutions?

  • djgtramdjgtram HUMember ✭✭
    edited May 12

    Your solution is obsolete as of version 2.5. Are there any updated solutions?

    Yes, there is. The plugin mentioned above does exactly this but I don't think you should need to use a Nuget plugin where a single class would do. Add a MainApplication to your Android project:

    public class MainApplication : Application, Application.IActivityLifecycleCallbacks {
      internal static Activity CurrentContext { get; private set; }
      public MainApplication(IntPtr handle, JniHandleOwnership transfer) :
        base(handle, transfer) {
      public override void OnCreate() {
      public override void OnTerminate() {
      public void OnActivityCreated(Activity activity, Bundle savedInstanceState) => CurrentContext = activity;
      public void OnActivityDestroyed(Activity activity) { }
      public void OnActivityPaused(Activity activity) { }
      public void OnActivityResumed(Activity activity) => CurrentContext = activity;
      public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
      public void OnActivityStarted(Activity activity) => CurrentContext = activity;
      public void OnActivityStopped(Activity activity) { }

    There is no need to refer to it, just put it among your source files where your main activity is, too. You can refer to the static MainApplication.CurrentContext from anywhere.

Sign In or Register to comment.