简体   繁体   中英

Why connectivity plugin network handler not working when navigation happens

In case the network connectivity isn't on to check if it is off, so, that I'm using to connectivity plug in.

I'm calling this code in ViewModelLocator class

Private static async void NetworkConnectivityChanged(object sender,Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e){}
CrossConnectivity.Current.ConnectivityChanged = NetworkConnectivityChanged;

In my windows app after navigating if network connectivity status changed … Here this event is not fire but if not using navigation, we change the network status and it happens it's working.

The workaround is to implement the native network change handler on Winphone or UWP side and stop handling of network change on PCL side for just Winphone and UWP. You can do this by checking the platform before handling.

Create a new Network.cs class with the following code(This detects if there is any change in network connection)

 public class InternetConnectionChangedEventArgs : EventArgs

{

    public InternetConnectionChangedEventArgs(bool isConnected)

    {

        this.isConnected = isConnected;

    }



    public bool IsConnected

    {

        get { return this.isConnected; }

    }



    private bool isConnected;

}



public static class Network

{

    public static event EventHandler<InternetConnectionChangedEventArgs>

        InternetConnectionChanged;



    static Network()

    {

        NetworkInformation.NetworkStatusChanged += (s) =>

        {

            if (InternetConnectionChanged != null)

            {

                var arg = new InternetConnectionChangedEventArgs(IsConnected);

                InternetConnectionChanged(null, arg);

            }

        };

    }



    public static bool IsConnected

    {

        get

        {

            var profile = NetworkInformation.GetInternetConnectionProfile();

            var isConnected = (profile != null

                && profile.GetNetworkConnectivityLevel() ==

                NetworkConnectivityLevel.InternetAccess);

            return isConnected;

        }

    }

}

Then in the app.xaml.cs in UWP or WinPhone register the network change handler in OnLaunched event like below

Network.InternetConnectionChanged += this.Network_InternetConnectionChanged;

and here is the event handler

 private void Network_InternetConnectionChanged(object sender,InternetConnectionChangedEventArgs e)

    {
      if(e.IsConnected){
         ///code to handle when the internet connectivity is there
      }
      else{
        //code to handle when the internet connectivity is lost
      }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM