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

gxwragnw  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(262)

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

nkkqxpd9

nkkqxpd91#

编辑:这可以很容易地用新的Xamarin Essentials Connectivity plugin完成,只需按照那里的说明:D

在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();
        });
}
zc0qhyus

zc0qhyus2#

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

检测连接更改

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

连接性的变化

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

/// <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}");
  };

相关问题