【问题标题】:Always Check if there is Internet Connection Xamarin forms始终检查是否存在 Internet 连接 Xamarin 表单
【发布时间】:2018-04-01 19:20:44
【问题描述】:

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

【问题讨论】:

  • Connectivity 插件具有在连接发生变化时触发的事件 - 这怎么不能满足您的要求?
  • 我不知道,我会检查文档,就像@Alessandro Caliaro 所做的那样。

标签: c# xamarin xamarin.forms


【解决方案1】:

编辑:这可以通过新的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();
        });
}

【讨论】:

  • 这个有点用,不支持导航,那怎么导航到另一个页面呢?
  • @Phill 为什么不尝试使用弹出窗口而不是页面?
  • 我在第二页中使用了上面的代码,而不是 app.cs,现在使用弹出窗口进行导航可以正常工作。非常感谢。
  • @Phill ,您可以使用 -> new NavigationPage().PushAsync(new YourPageWhenThereIsNoConnection()) 获得该方法
【解决方案2】:

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

检测连接变化

通常您可能需要根据网络变化通知您的用户或做出响应。您可以通过订阅几个不同的事件来做到这一点。

连接性变化

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

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

【讨论】:

  • 感谢他们为研究他们提供的现有工具所做的努力。干得好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
相关资源
最近更新 更多