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.