检查Xamarin Android中的Internet是打开还是关闭

时间:2015-10-26 10:05:45

标签: android xamarin mvvmcross internet-connection

我正在开发Xamarin Android应用程序。在继续我的下一个片段之前,我想检查 Internet连接并告知用户有关它的信息?我该如何实现呢?如何在用户开启互联网后刷新整个片段? 任何建议或意见将不胜感激!

3 个答案:

答案 0 :(得分:11)

要获取网络状态,您可以在活动中使用以下方法:

 public bool IsOnline()
    {
        var cm = (ConnectivityManager)GetSystemService(ConnectivityService);
        return cm.ActiveNetworkInfo == null ? false : cm.ActiveNetworkInfo.IsConnected;
    }

如果我从这句话中正确地理解你:And how to refresh whole fragment after user switch-on the internet,你想要在连接状态发生任何变化时检测到,因此你绝对需要使用broadcast receivers

首先,您应该使用名为ConnectionStatusChanged的简单事件实现广播接收器,如下所示:

[BroadcastReceiver()]
public class NetworkStatusBroadcastReceiver : BroadcastReceiver
{

    public event EventHandler ConnectionStatusChanged;

    public override void OnReceive(Context context, Intent intent)
    {
        if (ConnectionStatusChanged != null)
            ConnectionStatusChanged(this, EventArgs.Empty);
    }
}

然后在您的活动中(例如,在OnCreate()方法中,无关紧要)创建该接收器的实例并注册它:

var _broadcastReceiver = new NetworkStatusBroadcastReceiver();
_broadcastReceiver.ConnectionStatusChanged += OnNetworkStatusChanged;
Application.Context.RegisterReceiver(_broadcastReceiver, 
new IntentFilter(ConnectivityManager.ConnectivityAction));

以下是事件处理程序的主体:

private void OnNetworkStatusChanged(object sender, EventArgs e)
    {
       if(IsOnline()){
        Toast.MakeText(this, "Network Activated", ToastLength.Short).Show();
        // refresh content fragment.
       }
    }

简而言之,NetworkStatusBroadcastReceiver收到设备网络状态的任何变化,并调用ConnectionStatusChanged(当用户启用数据流量或WiFi连接时),然后您捕获该事件,使用IsOnline()方法检查网络状态。非常简单。

答案 1 :(得分:4)

您可以使用MVVMCross插件:Connectivity

它会暴露一个布尔值

/// <summary>
/// Gets if there is an active internet connection
/// </summary>
bool IsConnected { get; }

和改变状态的代表

/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged; 

答案 2 :(得分:1)

试试这个:

NetworkStatus internetStatus = Reachability.InternetConnectionStatus();

if(!Reachability.IsHostReachable("http://google.com")) {
    // Put alternative content/message here
}
else
{
    // Put Internet Required Code here
}