如果没有打开网络连接以检查它是否已关闭,那么,我正在使用连接插件。
我在 ViewModelLocator 类中调用此代码
Private static async void NetworkConnectivityChanged(object sender,Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e){}
CrossConnectivity.Current.ConnectivityChanged = NetworkConnectivityChanged;
在我的Windows应用程序导航后,如果网络连接状态发生变化...此处此事件不会触发,但如果不使用导航,我们会更改网络状态,并且它会发生它正在运行。
答案 0 :(得分:4)
解决方法是在Winphone或UWP端实施 原生网络更改处理程序 ,并停止处理PCL端的网络更改,仅用于Winphone和UWP。您可以在处理之前检查平台来执行此操作。
使用以下代码创建一个新的Network.cs类(这将检测网络连接是否有任何更改)
public class InternetConnectionChangedEventArgs : EventArgs
{
public InternetConnectionChangedEventArgs(bool isConnected)
{
this.isConnected = isConnected;
}
public bool IsConnected
{
get { return this.isConnected; }
}
private bool isConnected;
}
public static class Network
{
public static event EventHandler<InternetConnectionChangedEventArgs>
InternetConnectionChanged;
static Network()
{
NetworkInformation.NetworkStatusChanged += (s) =>
{
if (InternetConnectionChanged != null)
{
var arg = new InternetConnectionChangedEventArgs(IsConnected);
InternetConnectionChanged(null, arg);
}
};
}
public static bool IsConnected
{
get
{
var profile = NetworkInformation.GetInternetConnectionProfile();
var isConnected = (profile != null
&& profile.GetNetworkConnectivityLevel() ==
NetworkConnectivityLevel.InternetAccess);
return isConnected;
}
}
}
然后在UWP或WinPhone的app.xaml.cs中注册 OnLaunched 事件中的网络更改处理程序
Network.InternetConnectionChanged += this.Network_InternetConnectionChanged;
这是事件处理程序
private void Network_InternetConnectionChanged(object sender,InternetConnectionChangedEventArgs e)
{
if(e.IsConnected){
///code to handle when the internet connectivity is there
}
else{
//code to handle when the internet connectivity is lost
}
}