我目前正在使用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
。当你需要在活动上下文之外使用活动时,如何从应用程序上下文获取当前活动对象?
this
来传递对象实例的基本概念? - SquonkAndroidActivity
对象的类中调用的。它包含在一个不知道当前活动对象的类中,但可以访问Application.Context
对象。 - Michael Kniskern