Forms.Context已过时,所以我应该如何获取单个活动应用程序的“活动"?

编程入门 行业动态 更新时间:2024-10-25 22:33:28
本文介绍了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已过时,所以我应该如何获取单个活动应用程序的“活动"?

本文发布于:2023-10-28 08:40:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   所以我   Forms   Context   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!