Check internet Connection on phone

隐身守侯 提交于 2019-12-05 12:28:55

The emulator always returns NetworkInterface.GetIsNetworkAvailable() as true, even if you emulate network conditions as having no network.

I faced this problem myself and the only truly way of testing this behaviour is to deploy the application to a physical device running Windows Phone and test it with the data turned off.

I am using following code to check if the device has access to internet with if it is connected to wifi or data connection..

 public void UpdateNetworkInformation()
    {
        // Get current Internet Connection Profile.
        ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();

        //air plan mode is on...
        if (internetConnectionProfile == null)
        {
            Is_Connected = false;
            return;
        }

        //if true, internet is accessible.
        this.Is_InternetAvailable = internetConnectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;

        // Check the connection details.
        else if (internetConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)// Connection is not a Wi-Fi connection. 
        {
            Is_Roaming = internetConnectionProfile.GetConnectionCost().Roaming;

            /// user is Low on Data package only send low data.
            Is_LowOnData = internetConnectionProfile.GetConnectionCost().ApproachingDataLimit;

            //User is over limit do not send data
            Is_OverDataLimit = internetConnectionProfile.GetConnectionCost().OverDataLimit;

        }
        else //Connection is a Wi-Fi connection. Data restrictions are not necessary. 
        {
            Is_Wifi_Connected = true;
        }
    }

Edit: And for simple internet connection you can use below code.

  System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

Hope this helps!

NetworkInterface.GetIsNetworkAvailable() checks the network connection and not the internet connection. If you are in any kind of network, then it will return true whether internet is present or not.

You can check the internet connection as following:

using System.Net

private bool IsOnline() 
{
    try
    {
        IPHostEntry iPHostEntry = Dns.GetHostEntry("www.wikipedia.com");
        return true;
    }
    catch (SocketException ex) 
    {
        return false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!