2

For now I use this:

var activity = (Activity)Forms.Context;

But what I should use instead?

According to accepted answer here I should use Android.App.Application.Context: Xamarin.Forms: Forms.Context is obsolete

But I can't cast it into Activity.

Is here any workaround?

UPD: I need it to close application from library.

InfernumDeus
  • 1,185
  • 1
  • 11
  • 33
  • 1
    Without any context to where you are using that code a direct answer is hard, but you can use, CurrentActivityPlugin, a hack for sure, but it works... https://github.com/jamesmontemagno/CurrentActivityPlugin – SushiHangover Jul 10 '18 at 06:54
  • Added to the question. – InfernumDeus Jul 10 '18 at 06:55
  • 1
    `need it for library to close application` So it is a `Xamirin.Android` but again that does not really detail how/who/where of what is instancing objects in that library and can you pass an Activity content into a constructor, an additional parameter on a method, does that library have any visible View/ViewGroup subclasses in it that are being displayed and thus you can use the context of the View, etc... – SushiHangover Jul 10 '18 at 07:02
  • @SushiHangover, It dosn't implied to have any code for UI part and doesn't take instance of Activity. – InfernumDeus Jul 10 '18 at 07:18

1 Answers1

5

Solution one: Use CurrentActivityPlugin library. After setting up it correctly:

var activity = CrossCurrentActivity.Current.Activity;

Solution two: Define a static instance in MainActivity class:

public class MainActivity : FormsAppCompatActivity
{
    public static FormsAppCompatActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        Instance = this;

        //other codes
    }
}

And use that like so:

var activity = MainActivity.Instance;

Note: Obviously we should use solution two when application's entry point is MainActivity, and not other ones such as background service, broadcast receiver, etc, otherwise MainActivity.Instance might be null. For those cases we can either use solution one, or define a static instance in those entry points too.

VahidShir
  • 2,066
  • 2
  • 17
  • 27