InfernumDeus
InfernumDeus

Reputation: 1202

Forms.Context is obsolete so how should I get Activity of my single activity application?

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

Answers (1)

VahidShir
VahidShir

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

Related Questions