How to check the internet connection availability

2019-03-25 06:37发布

I'm developing Windows Phone 8 application. In this application, I have to connect to the server to get the data.

So Before connecting to the server, I want to check whether the internet connection available or not to the device. If the internet connection is available, then only I'll get the data from the server, Otherwise I'll show an error message.

Please tell me how to do this in Windows Phone 8.

7条回答
Lonely孤独者°
2楼-- · 2019-03-25 07:07

This is how I did it...

class Internet
{
    static DispatcherTimer dispatcherTimer;

    public static bool Available = false;

    public static async void StartChecking()
    {
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(IsInternetAvailable1);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 10); //10 Secconds or Faster
        await IsInternetAvailable(null, null);
        dispatcherTimer.Start();
    }

    private static async void IsInternetAvailable1(object sender, EventArgs e)
    {
        await IsInternetAvailable(sender, e);
    }

    private static async Task IsInternetAvailable(object sender, EventArgs ev)
    {
        string url = "https://www.google.com/";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "text/plain; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                                 httpWebRequest.EndGetRequestStream, null))
        {
            string json = "{ \"302000001\" }"; //Post Anything

            byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);

            await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);

            WebClient hc = new WebClient();
            hc.DownloadStringCompleted += (s, e) =>
            {
                try
                {
                    if (!string.IsNullOrEmpty(e.Result))
                    {
                        Available = true;
                    }
                    else
                    {
                        Available = false;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is TargetInvocationException)
                    {
                        Available = false;
                    }
                }
            };
            hc.DownloadStringAsync(new Uri(url));
        }
    }

}

Since windows phone 8 does not have a way of checking internet connectivity, you need to do it by sending a POST HTTP request. You can do that by sending it to any website you want. I chose google.com. Then, check every 10 seconds or less to refresh the state of the connection.

查看更多
女痞
3楼-- · 2019-03-25 07:10

You can use NetworkInformation.GetInternetConnectionProfile to get the profile that is currently in use, from this you can work out the connectivity level. More info here GetInternetConnectionProfile msdn

Example of how you might use.

    private void YourMethod()
    {
         if (InternetConnection) {

           // Your code connecting to server

         }
    }

    public static bool InternetConnection()
    {
        return NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel() >= NetworkConnectivityLevel.InternetAccess;
    }
查看更多
迷人小祖宗
4楼-- · 2019-03-25 07:16

NetworkInterface.GetIsNetworkAvailable() returns the status of the NICs.

Depending on the status you can ask if the connectivity is established by using:

ConnectionProfile-Class of Windows Phone 8.1 which uses the enum NetworkConnectivityLevel:

  • None
  • Local Access
  • Internet Access

This code should do the trick.

bool isConnected = NetworkInterface.GetIsNetworkAvailable();
if (isConnected)
{
    ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
    NetworkConnectivityLevel connection = InternetConnectionProfile.GetNetworkConnectivityLevel();
    if (connection == NetworkConnectivityLevel.None || connection == NetworkConnectivityLevel.LocalAccess)
    {
        isConnected = false;
    }
}
if(!isConnected)
    await new MessageDialog("No internet connection is avaliable. The full functionality of the app isn't avaliable.").ShowAsync();
查看更多
神经病院院长
5楼-- · 2019-03-25 07:18

There can be some delay in response of web request. Therefore this method may not be fast enough for some applications. This will check the internet connection on any device. A better way is to check whether port 80, the default port for http traffic, of an always online website.

public static bool TcpSocketTest()
    {
        try
        {
            System.Net.Sockets.TcpClient client =
                new System.Net.Sockets.TcpClient("www.google.com", 80);
            client.Close();
            return true;
        }
        catch (System.Exception ex)
        {
            return false;
        }
    }
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-03-25 07:21

You can use NetworkInterface.GetIsNetworkAvailable() method. It returns true if network connection is available and false if not. And don't forget to add using Microsoft.Phone.Net.NetworkInformation or using System.Net.NetworkInformation if you are in PCL.

查看更多
SAY GOODBYE
7楼-- · 2019-03-25 07:26
public static bool checkNetworkConnection()
{
    var ni = NetworkInterface.NetworkInterfaceType;

    bool IsConnected = false;
    if ((ni == NetworkInterfaceType.Wireless80211)|| (ni == NetworkInterfaceType.MobileBroadbandCdma)|| (ni == NetworkInterfaceType.MobileBroadbandGsm))
        IsConnected= true;
    else if (ni == NetworkInterfaceType.None)
        IsConnected= false;
    return IsConnected;
}

Call this function and check whether internet connection is available or not.

查看更多
登录 后发表回答