4

我想检查我的手机是否可以连接到互联网。我已经看到了几个问题。其中之一是Question。它说要使用NetworkInterface.GetIsNetworkAvailable()它,我试过了。我已经断开了我的电脑与互联网的连接,还关闭了DataConnection模​​拟器,但这NetworkInterface.GetIsNetworkAvailable()总是返回 true。但同时我也检查了NetworkInterfaceType.None它,有趣的是它即将为空。谁能解释我在哪里缺少信息?

尝试:-

public static void CheckNetworkAvailability()
    {
       // this is coming true even when i disconnected my pc from internet.
       // i also make the dataconnection off of the emulator
        var fg = NetworkInterface.GetIsNetworkAvailable();

        var ni = NetworkInterface.NetworkInterfaceType;
        // this part is coming none  
        if (ni == NetworkInterfaceType.None)
            IsConnected = false;

    }

任何帮助表示赞赏:)

4

3 回答 3

9

我正在使用以下代码检查设备是否可以访问互联网,以及它是否连接到 wifi 或数据连接..

 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;
        }
    }

编辑: 对于简单的互联网连接,您可以使用以下代码。

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

希望这可以帮助!

于 2014-08-04T13:06:15.540 回答
7

NetworkInterface.GetIsNetworkAvailable()即使您将网络条件模拟为没有网络,模拟器也始终返回true。

我自己也遇到过这个问题,测试这种行为的唯一真正方法是将应用程序部署到运行 Windows Phone 的物理设备上,并在关闭数据的情况下对其进行测试。

于 2014-08-04T11:26:14.150 回答
4

NetworkInterface.GetIsNetworkAvailable()检查network connection而不是 internet connection. 如果您在任何类型的网络中,那么true无论是否internet存在,它都会返回。

您可以按以下方式检查互联网连接:

using System.Net

private bool IsOnline() 
{
    try
    {
        IPHostEntry iPHostEntry = Dns.GetHostEntry("www.wikipedia.com");
        return true;
    }
    catch (SocketException ex) 
    {
        return false;
    }
}
于 2014-08-04T11:56:29.460 回答