Windows Phone 8.1: Check Internet Connection

2019-04-08 15:24发布

问题:

How can I know if the phone has internet connection? (Whether WiFi or Data)

Sometimes the phone is connecting to WiFi without internet connection like HotSpots. So I want a code to know if the phone is connecting to internet.

回答1:

You can simply try:

 if (NetworkInformation.GetInternetConnectionProfile() == null)
        {
            //no connection
        }

As you can see in this msdn documentation:NetworkInformation.GetInternetConnectionProfile

It will return null if there is "no connection profile with a suitable connection"

You can also check explicity the "Internet Access" level with this: NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess

I Think this will work also in universal app.



回答2:

The below Method works for me simply to check if the device is connected to internet or not even in universal windows app. After creating the connection class you can simply use it anywhere just by instantiating this class...

public class Connection
{
   public bool CheckInternetAccess()
   {
        var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
        var HasInternetAccess = (connectionProfile != null &&
                             connectionProfile.GetNetworkConnectivityLevel() ==
                             NetworkConnectivityLevel.InternetAccess);
        return HasInternetAccess;
   }
}

To use this class simply..

 Connection objConnection = new Connection();
 if(objConnection.CheckInternetAccess()==true)
 {
   //todo
 }
 else
 {//todo}


回答3:

What you want is a captive portal, which is pretty much a page that users connect to, to test whether their internet connection is working, it can be explained here in greater detail.

These open source projects look promising:

  1. WiFiDog
  2. ChilliSpot

Good Luck!



回答4:

Please consider checking internet in background thread

if (await Task.Run(() =>NetworkInterface.GetIsNetworkAvailable())
{
   //Wifi or Cellular
}
else
{
   // No internet
}