总是检查是否有互联网连接Xamarin形式
我正在做一个Xamarin表单应用程序,我想检查每一秒如果有互联网连接,如果连接丢失,程序应该去不同的页面。 我使用的插件“Xam.Plugin.Connectivity”,但没有做我想做的。 有可能做我想要的吗?总是检查是否有互联网连接Xamarin形式
这样创建您的App.cs(或App.xaml.cs)的方法:
private async void CheckConnection()
{
if(!CrossConnectivity.Current.IsConnected)
await Navigation.PushAsync(new YourPageWhenThereIsNoConnection());
else
return;
}
并使用它在你的主应用程序的方法是这样的:
public App()
{
InitializeComponent();
var seconds = TimeSpan.FromSeconds(1);
Xamarin.Forms.Device.StartTimer(seconds,
() =>
{
CheckConnection();
});
}
这有点作品,导航不支持,那么naviagate怎么能到另一个页面呢? – Phill
你能帮忙吗? 谢谢。 – Phill
@Phill为什么不尝试使用弹出窗口而不是页面? – FabriBertani
没用过,不过这是一个关于你正在使用
检测连接的变化
通常你可能需要通知用户或基于网络的变化做出反应的插件文档。您可以通过订阅几个不同的事件来完成此操作。在连接
当任何网络连接的不断积累
变化,改变或丢失,你可以为一个事件火灾登记:
/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged;
You will get a ConnectivityChangeEventArgs with the status if you are connected or not:
public class ConnectivityChangedEventArgs : EventArgs
{
public bool IsConnected { get; set; }
}
public delegate void ConnectivityChangedEventHandler(object sender, ConnectivityChangedEventArgs e);
CrossConnectivity.Current.ConnectivityChanged += async (sender, args) =>
{
Debug.WriteLine($"Connectivity changed to {args.IsConnected}");
};
变化连接类型
当任何网络连接类型改变时,该事件被触发。通常它还伴随着一个ConnectivityChanged事件。
/// <summary>
/// Event handler when connection type changes
/// </summary>
event ConnectivityTypeChangedEventHandler ConnectivityTypeChanged;
When this occurs an event will be triggered with EventArgs that have the most recent information:
public class ConnectivityTypeChangedEventArgs : EventArgs
{
public bool IsConnected { get; set; }
public IEnumerable<ConnectionType> ConnectionTypes { get; set; }
}
public delegate void ConnectivityTypeChangedEventHandler(object sender, ConnectivityTypeChangedEventArgs e);
Example:
CrossConnectivity.Current.ConnectivityTypeChanged += async (sender, args) =>
{
Debug.WriteLine($"Connectivity changed to {args.IsConnected}");
foreach(var t in args.ConnectionTypes)
Debug.WriteLine($"Connection Type {t}");
};
Connectivity插件有连接发生变化时会触发的事件 - 这不符合您的要求? – Jason
我不知道,我会检查文档,就像@Alessandro Caliaro那样。 – Phill