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

☆樱花仙子☆ 提交于 2020-02-23 06:02:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/51258783/forms-context-is-obsolete-so-how-should-i-get-activity-of-my-single-activity-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!