Forms.Context已过时,所以我应该如何获取单个活动应用程序的“活动"? [英] Forms.Context is obsolete so how should I get Activity of my single activity application?

查看:107
本文介绍了Forms.Context已过时,所以我应该如何获取单个活动应用程序的“活动"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我使用这个:

var activity = (Activity)Forms.Context;

但是我应该用什么代替?

But what I should use instead?

根据此处接受的答案,我应该使用Android.App.Application.Context: Xamarin.Forms:Forms.Context已过时

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

但是我无法将其投放到Activity.

But I can't cast it into Activity.

这里有什么解决方法吗?

Is here any workaround?

UPD :我需要它来从库中关闭应用程序.

UPD: I need it to close application from library.

推荐答案

解决方案一: 使用 CurrentActivityPlugin 库.正确设置后:

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

var activity = CrossCurrentActivity.Current.Activity;

解决方案二: 在MainActivity类中定义一个静态实例:

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
    }
}

并像这样使用它:

var activity = MainActivity.Instance;

注意:显然,当应用程序的入口点是MainActivity时,我们应该使用解决方案二,而不是诸如后台服务,广播接收器等其他入口,否则MainActivity.Instance可能为null.对于这些情况,我们可以使用解决方案一,也可以在这些入口点中定义一个静态实例.

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.

这篇关于Forms.Context已过时,所以我应该如何获取单个活动应用程序的“活动"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆