Windows Phone 8.1: Check Internet Connection

2019-04-08 15:44发布

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.

4条回答
虎瘦雄心在
2楼-- · 2019-04-08 15:51

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!

查看更多
Evening l夕情丶
3楼-- · 2019-04-08 15:59

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}
查看更多
唯我独甜
4楼-- · 2019-04-08 16:04

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.

查看更多
混吃等死
5楼-- · 2019-04-08 16:08

Please consider checking internet in background thread

if (await Task.Run(() =>NetworkInterface.GetIsNetworkAvailable())
{
   //Wifi or Cellular
}
else
{
   // No internet
}
查看更多
登录 后发表回答