从Application.Context获取当前活动-MonoAndroid。

10

我目前正在使用Xamarin.Forms开发一个应用程序,该程序将在Android和iOS平台上提供。当应用程序在设备上首次加载时,我会检查设备是否有可用的互联网连接。如果没有可用的互联网连接,我想显示一个对话框。

下面是我用来检查Xamarin.Forms.ContentPage上的互联网连接的代码片段:

if(App.Connectivity.IsNetworkConnectivityAvailable())
{
    App.Notification.DisplayLocalNotifications("No Internet", "You need an internet connection to access certain application content");
}

我正在使用依赖注入来构建适用于每个适当环境处理对话框的适当模块。Android抛出了以下异常:

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application Here is the code for the DisplayLocalNotification method on the Android:

public void DisplayLocalNotification(string title, string content)
{        
     AlertDialog.Builder builder = new AlertDialog.Builder(Application.Context)
          .SetTitle(title)
          .SetMessage(content)
          .SetCancelable(true)
          .SetPositiveButton("OK", (EventHandler<DialogClickEventArgs>) null);

      AlertDialog alert = builder.Create();
      alert.Show();

      var okBtn = alert.GetButton((int)DialogButtonType.Positive);

      okBtn.Click += (sender, args) =>
      {
           alert.Dismiss();
      };
}

做了一些研究后,我需要将当前活动传递到AlertDialog.Builder构造函数中,而不是使用Application.Context。当你需要在活动上下文之外使用活动时,如何从应用程序上下文获取当前活动对象?


Xamarin是否没有通过简单地使用this来传递对象实例的基本概念? - Squonk
@Squonk - 是的,确实如此,但是这段代码并不是从继承自AndroidActivity对象的类中调用的。它包含在一个不知道当前活动对象的类中,但可以访问Application.Context对象。 - Michael Kniskern
1
如果您没有活动的“Activity”,那么就不能保证存在一个,必须有某些东西是活动/可见的,才能创建“AlertDialog”,在这种情况下,您应该使用该“Activity”“Context”。在Android术语中,“Application”没有可见性,基本上只是一个框架。 - Squonk
希望它有所帮助 http://stackoverflow.com/a/28423385/185022 - AZ_
1个回答

24

Xamarin.Forms Android平台的代码应该将当前Activity分配到Forms.Context属性中。这是静态Forms类,如果你进行调试,你会看到Forms.Context是一个Activity。

public static class Forms
{
    public static Context Context { get; }
    public static bool IsInitialized { get; }

    public static event EventHandler<ViewInitializedEventArgs> ViewInitialized;

    public static void Init(Activity activity, Bundle bundle);
}

3
是的。Forms.Context 是当前活动。 - SKall
2
谢谢!用AlertDialog.Builder builder = new AlertDialog.Builder(Forms.Context)替换AlertDialog.Builder builder = new AlertDialog.Builder(Application.Context)可以解决问题。 - Michael Kniskern
7
Xamarin需要更好的文档说明Forms.Context对象。 - Timothy Lee Russell
9
一般而言,它们需要更好的文档记录。 - SKall
我甚至不想知道你如何从常规的Xamarin中访问Forms.Context - Reynevan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接