How to check the internet connection availability in windows phone 8 application
Asked Answered
Q

7

12

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.

Quiet answered 19/12, 2013 at 8:36 Comment(3)
#13617517 Maybe this link can help you.Dissatisfactory
msdn.microsoft.com/en-us/library/… there is method available GetIsNetworkAvailableRoasting
Instead of the classic method no check network (noto the connection itself), I would make a webrequest and see the response message.Florella
E
13

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();
Ethban answered 13/10, 2014 at 19:27 Comment(2)
This was only tested in Windows Phone 8.1, I don't know if it's applicable to older versions of WP.Ethban
I don't know why, but in the emulator this method always return true for me, even if network is set to no network.Spaniel
T
7
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.

Timbuktu answered 20/12, 2013 at 7:19 Comment(2)
Wouldn't it be easier to check if ni != NetworkInterfaceType.None and return true, and return false in the else-Statement?Wintergreen
That doesn't work when you are connected to a wifi and the network is not connected to the Internet.Thelmathem
F
0

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.

Foregut answered 8/4, 2014 at 5:30 Comment(1)
That doesn't work when you are connected to a wifi and the network is not connected to the Internet.Thelmathem
L
0

Since this question appears in first result of google search for checking internet availability, I would put the answer for windows phone 8.1 XAML also. It has a little different APIs compared to 8.

//Get the Internet connection profile
string connectionProfileInfo = string.Empty;
try {
    ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

    if (InternetConnectionProfile == null) {
        NotifyUser("Not connected to Internet\n");
    }
    else {
        connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
        NotifyUser("Internet connection profile = " +connectionProfileInfo);
    }
}
catch (Exception ex) {
    NotifyUser("Unexpected exception occurred: " + ex.ToString());
}

For more reading go to MSDN How to retrieve network connection...

Latinist answered 12/4, 2015 at 5:25 Comment(0)
E
0

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;
    }
Experimentalize answered 14/4, 2015 at 3:32 Comment(0)
L
0

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.

Lewellen answered 5/5, 2016 at 15:9 Comment(0)
A
0

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;
        }
    }
Architect answered 23/3, 2017 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.