【发布时间】:2014-09-01 21:44:05
【问题描述】:
我目前正在使用Xamarin.Forms 开发一个应用程序,该应用程序将在 Android 和 iOS 平台上可用。当应用程序首次加载到设备上时,我会检查设备上是否有可用的互联网连接。如果互联网连接不可用,我想显示一个对话框。
这是我用来在Xamarin.Forms.ContentPage 上检查互联网的以下 sn-p 代码
if(App.Connectivity.IsNetworkConnectivityAvailable())
{
App.Notification.DisplayLocalNotifications("No Internet", "You need an internet connection to access certain application content");
}
我正在使用依赖注入来构建适当的模块,以便为每个适当的环境处理对话框。 Android 抛出以下异常
Android.Views.WindowManagerBadTokenException: 无法添加窗口 -- 令牌 null 不适用于应用程序这是 Android 上的 DisplayLocalNotification 方法:
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 - 是的,确实如此,但这段代码不是从继承自
AndroidActivity对象的类中调用的。它包含在一个不知道当前活动对象但可以访问Application.Context对象的类中 -
如果您没有活动的
Activity,那么您不能保证存在一个,为了创建AlertDialog,您应该使用某些东西必须是活动的/可见的ActivityContext。 Android 术语中的Application没有可见性,基本上是一个骨架框架。
标签: android dependency-injection xamarin xamarin.android xamarin.forms