Reputation: 1202
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.
Upvotes: 2
Views: 1987
Reputation: 2106
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.
Upvotes: 5