始终检查是否存在Internet连接Xamarin表单

Phi*_*ill 5 c# xamarin xamarin.forms

我正在做一个xamarin表单应用程序,我想检查每一秒是否有互联网连接,如果连接丢失,程序应该去不同的页面.我使用插件"Xam.Plugin.Connectivity",但没有做我想要的.有可能做我想要的吗?

Fab*_*ani 12

在App.cs(或App.xaml.cs)中创建一个方法,如下所示:

private async void CheckConnection()
{
    if(!CrossConnectivity.Current.IsConnected)
         await Navigation.PushAsync(new YourPageWhenThereIsNoConnection());
    else
         return;
}
Run Code Online (Sandbox Code Playgroud)

并在您的主应用程序方法上使用它,如下所示:

public App()
{
    InitializeComponent();

    var seconds = TimeSpan.FromSeconds(1);
    Xamarin.Forms.Device.StartTimer(seconds,
        () =>
        {
             CheckConnection();
        });
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*aro 8

从未使用过,但这是关于您正在使用的插件的文档

检测连接变化

通常,您可能需要通知您的用户或根据网络更改做出响应.您可以通过订阅几个不同的事件来完成此操作.

连通性的变化

获得,更改或丢失任何网络连接后,您可以注册要触发的事件:

/// <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}");
  };
Run Code Online (Sandbox Code Playgroud)

连通类型的变化

更改任何网络连接类型时,将触发此事件.通常它还伴随着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}");
  };
Run Code Online (Sandbox Code Playgroud)