Check if Internet is turned on in Xamarin Android

I am working on Xamarin apps for Android. Before moving on to the next fragment, I want to check the Internet connection and inform the user about this? How can I implement this? And how to update the entire fragment after the user is connected to the Internet?
Any advice or suggestions would be appreciated!

+7
android internet-connection xamarin mvvmcross
source share
3 answers

Try the following:

NetworkStatus internetStatus = Reachability.InternetConnectionStatus(); if(!Reachability.IsHostReachable("http://google.com")) { // Put alternative content/message here } else { // Put Internet Required Code here } 
+1
source share

To get the status of a network, you can use the following method in your work:

  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 there are any changes in the connection state, so you absolutely need to use broadcast receivers .

First of all, you should implement a broadcast receiver with a simple event called 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 (for example, in the OnCreate() method, it does not matter) create an instance of this 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 shorten the long history, NetworkStatusBroadcastReceiver receives any change in the network status of the device and calls ConnectionStatusChanged (when the user allows data traffic or WiFi connection). Then you catch this event and check the network status using the IsOnline() method. Very simple.

+8
source share

You can use the plugin MVVMCross: Connectivity

This will lead to the conclusion of Boolean

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

and the delegate is in a state of change

 /// <summary> /// Event handler when connection changes /// </summary> event ConnectivityChangedEventHandler ConnectivityChanged; 
+1
source share

All Articles