Check whether Internet is on or off in Xamarin Android

自古美人都是妖i 提交于 2019-12-05 03:37:58

Try this :

NetworkStatus internetStatus = Reachability.InternetConnectionStatus();

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

To get the network status you could use the following method in your activity:

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

If I understood you correctly from this sentence: And how to refresh whole fragment after user switch-on the internet, You want to detect, whenever any changes in the connection status happens, Therefore you absolutely need to use broadcast receivers.

First of all you should implement a broadcast receiver with a simple Event named ConnectionStatusChanged as follows:

[BroadcastReceiver()]
public class NetworkStatusBroadcastReceiver : BroadcastReceiver
{

    public event EventHandler ConnectionStatusChanged;

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

Then in your activity (in OnCreate() method for example, It doesn't matter) create an instance of that receiver and register it:

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

Here is the body of the event handler:

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

To cut the long story short, NetworkStatusBroadcastReceiver receives any change in the network status of the device and invokes the ConnectionStatusChanged (When user enables data traffic or WiFi connection), Then you catch that event and check for network status using IsOnline() method. Very simple.

You can use the MVVMCross plugin : Connectivity

It wil expose a boolean

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

and a delegate on change state

/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!