How to get notified when network connection change

2019-08-31 16:10发布

问题:

I have a requirement in my app where I need to display an image to indicate whether the app is connected to network or not.I was able to do it using the Connectivity Plugin by James Montemagno.But I want to implement it using Reachability class.When I implement the Reachability class the OnChange method never fires.When I turn ON or turn OFF the wifi the OnChange is never called.Can somebody guide me on how to achieve this?

 public static event EventHandler ReachabilityChanged;
static void OnChange(NetworkReachabilityFlags flags)
        {
            ReachabilityChanged?.Invoke(null, EventArgs.Empty);
        }

回答1:

Put below code in your PCL App()

CrossConnectivity.Current.ConnectivityChanged += (object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e) =>
{
    bool IsInternetConnected = e.IsConnected;
}

You can pass connectivity status using Messaging Center refer this



回答2:

Ok let me explain how use the Rehability.cs class

1) add this file in your project.

https://github.com/xamarin/ios-samples/blob/master/ReachabilitySample/reachability.cs

2) change the namespace for the name of your project .

3) Declare this variables in your ViewController like the image

 NetworkStatus remoteHostStatus, internetStatus, localWifiStatus;

4) In your ViewController add this method . The line TableView.ReloadData (); put the name of your table o item that you wanna update.

void UpdateStatus (object sender, EventArgs e)
    {
        remoteHostStatus = Reachability.RemoteHostStatus ();
        internetStatus = Reachability.InternetConnectionStatus ();
        localWifiStatus = Reachability.LocalWifiConnectionStatus ();
        TableView.ReloadData ();
    }

5) In the ViewDidLoad add this two lines

        UpdateStatus (null, null);
        Reachability.ReachabilityChanged += UpdateStatus;

for a more understand of the code download this example and run the app in you Visual studio . https://developer.xamarin.com/samples/monotouch/ReachabilitySample/

Regards