Check Internet connectivity

sunil.8167sunil.8167 USMember ✭✭

Hi,
Can anybody suggest me how to check internet connectivity for both iOS and Android commonly using xamarin forms?

Thanks,
sunil

Answers

  • PierceBogganPierceBoggan USForum Administrator, Xamarin Team, Developer Group Leader Xamurai

    Hi @sunil.8167!

    I'm not aware of a solution that works for both right out of the box. You could always use Xamarin.Form's DependencyService to create a simple solution.

    On a platform-specific level, there is plenty of code you can use that others have already written that would be of help:

    Our community has also created a project called Xamarin.Forms Labs, which also sports a Device service (currently in Beta) that can check internet connectivity.

    Also, moving this thread to Xamarin.Forms forum, as this isn't a community topic.

  • FW_AlexFW_Alex USMember

    Just FYI - I had the same question and I went down the Xamarin.Forms Labs route based on the recommendation above.

    I was wondering why it wasn't working, and then when I looked at the device-specific libraries, I noticed that they're coded to always return a null for the device.PhoneService.IsNetworkAvailable - so this is not implemented yet it seems!

  • rmarinhormarinho PTMember, Insider, Beta Xamurai

    @Alex.9530 thanks for the notice, we have that methods implemented to Windows phone but stiil missing some properties on IOS and Android, we gonna fix that, you can follow the issue here:

    https://github.com/XForms/Xamarin-Forms-Labs/issues/131

  • SKallSKall USMember ✭✭✭✭

    I pushed in initial implementations for both iOS and Android. If you are working against the GitHub source any help in testing would be welcome. We probably have to implement a separate interface for the network as the phone service is only available on devices with call capabilities and not on tablets with WiFi.

  • SagarGPSagarGP INMember ✭✭

    Hi,

    Do the current version of Xamarin.forms has support to check check internet connectivity?

    Thanks,
    Sagar

  • pwojtowiczpwojtowicz USMember ✭✭

    Hello,

    anybody has worked out solution for this? I am interested in solution for Android, Windows Phone, iOS and both for phones and tablets.

    Thanks, Piotr

  • SergiuCosminSergiuCosmin USMember ✭✭

    hello,

    I think I found something that will do the trick if you are using MVVMCross, there is nice plugin here that does the job nicely:

    https://github.com/aritchie/acrmvvmcross/tree/master/Acr.MvvmCross.Plugins.Network

  • smAshleysmAshley USMember, University
  • JohnHardmanJohnHardman GBUniversity mod

    Be aware that solutions that rely on pinging a remote device may be unreliable if the remote device is configured to not respond to pings, or if firewalls block ICMP messages used by ping.

  • lk786lk786 USMember

    Hi All Used this Link for making Dependency service regarding above explained problem
    http://www.codeproject.com/Tips/870548/Xamarin-forms-Check-network-connectivity-in-iOS-an
    for this Dependency service need to be created

  • lk786lk786 USMember

    and for Windows platform use this

    public static bool getIsInternetAccessAvailable()
    {
    switch(NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel())
    {
    case NetworkConnectivityLevel.InternetAccess:
    return true;
    default:
    return false;
    }
    }

  • BharatJogaranaBharatJogarana USMember ✭✭

    How to terminate app?

  • BharatJogaranaBharatJogarana USMember ✭✭

    iNetRequest.GetResponse ();
    here "GetResponse()" is error not find properly.

  • BharatJogaranaBharatJogarana USMember ✭✭

    **Hi, **

    Can u help me regarding network connectivity issue in windows phone xamarin app.

    bool isConnected = NetworkInterface.GetIsNetworkAvailable(); this code always return TRUE when internet is connected or disconnect both time bool isConnected = NetworkInterface.GetIsNetworkAvailable(); these returns TRUE.

    any else condition where bool isConnected = NetworkInterface.GetIsNetworkAvailable(); this condition will return FALSE then help regarding connectivity manager using in Android.

    Please check attached screenshots.

  • ChristophThielChristophThiel DEMember ✭✭

    Hi @BharatJogarana

    my sample above is a synchronous method that works in a Shared Project on iOS and Android.

    For PCL projects and Windows Phone you need to use asynchronous methods.
    You could find a sample in Charles Petzold's BookPreview Chapter 20 Page 677.

    Look Here
    .

  • giorgilekveishviligiorgilekveishvili GEMember ✭✭
    edited July 2016

    `private bool isInternetAviable()
    {

            try
            {
                Ping myPing = new Ping();
                String host = "google.com";
                byte[] buffer = new byte[32];
                int timeout = 1000;
                PingOptions pingOptions = new PingOptions();
                PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    

    }`

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    @giorgilekveishvili
    Try that on an actual device that is connected to mobile data not WIFI with no data bundles loaded and also no Airtime/money on your account and the Ping still returns true, not false as it should.

    Android...
    I would recommend using:

     public bool isOnline()
            {
                Runtime runtime = Runtime.GetRuntime();
                try
                {
                    Java.Lang.Process ipProcess = runtime.Exec("/system/bin/ping -c 1 8.8.8.8");
                    int exitValue = ipProcess.WaitFor();
                    return (exitValue == 0);
                }
                catch (Java.IO.IOException e) { e.PrintStackTrace(); }
                catch (InterruptedException e) { e.PrintStackTrace(); }
    
                return false;
            } 
    

    I found these results more accurate.

    Permission Required:

    <uses-permission android:name="android.permission.INTERNET" />

    Source: http://stackoverflow.com/a/27312494

  • This returns a bool:

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

  • JohnHardmanJohnHardman GBUniversity mod

    @ChristophThiel @giorgilekveishvili - If you're planning on having users in China, be aware that the Great Firewall of China may block access to Google. You may want to use an alternative if you believe your user is based in mainland China.

    @giorgilekveishvili - As per comment earlier on thread, relying on ping can cause issues, as a result of firewalls not allowing some ICMP stuff through, or as a result of servers disabling ping.

  • Scott_WolfScott_Wolf INMember ✭✭

    @MattFedorovich It's does not seems to be working. I've used Flight mode.

  • AnikAnik INMember

    Hi @Sunil,

    check this out:

    public bool CheckInternetConnection ()
    {
    string CheckUrl = "https://www.google.co.in";
    try{
    HttpWebRequest iNetRequest = (HttpWebRequest)WebRequest.Create (CheckUrl);
    iNetRequest.Timeout = 5000;
    WebResponse iNetResponse = iNetRequest.GetResponse ();
    iNetResponse.Close ();
    return true;
    } catch (WebException ex)
    {
    return false;
    }
    }

  • y_SBSICy_SBSIC USMember ✭✭✭

    Dependency Services is best for these type of issue, please check bellow link : https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/battery-info/

  • WindyhenWindyhen USMember ✭✭

    @ChristophThiel said:
    Here is an easy way without any plugins.

          public bool CheckInternetConnection ()
          {
              string CheckUrl = "http://google.com";
    
              try {
                  HttpWebRequest iNetRequest = (HttpWebRequest)WebRequest.Create (CheckUrl);
    
                  iNetRequest.Timeout = 5000;
    
                  WebResponse iNetResponse = iNetRequest.GetResponse ();
    
                  // Console.WriteLine ("...connection established..." + iNetRequest.ToString ());
                  iNetResponse.Close ();
                  
                  return true;
    
              } catch (WebException ex) {
                  
                  // Console.WriteLine (".....no connection..." + ex.ToString ());
    
                  return false;
              }
          }
    

    returns true, if internet connection was established and false, if not.
    Works for me! :smile:

    GetReponse not available in PCL

  • ChristophThielChristophThiel DEMember ✭✭

    @Windyhen
    In PCL you need to use async methods

  • PritamJPritamJ INMember

    @Christoph Thiel
    thnks :smile:

  • HarshitaHarshita INMember ✭✭✭

    Full guide here :smile:

  • BoomShankarBoomShankar USMember ✭✭

    Following instructions from the above members. Here's what I did so that the app asynchronously keeps checking if the internet is present every five seconds.

    `async void CheckInternetConnectionASync()
    {
    while (true)
    {
    string CheckUrl = "http://google.com";

                try
                {
                    HttpWebRequest iNetRequest = (HttpWebRequest)WebRequest.Create(CheckUrl);
                    iNetRequest.ContinueTimeout = 5000;
                    WebResponse iNetResponse = await iNetRequest.GetResponseAsync();
                    iNetResponse.Dispose();
    
                    log.i("Internet connection present.");
                }
                catch (WebException ex)
                {
                    log.e("CheckInternetConnectionASync: No internet connection", ex);
                    await DisplayAlert("No Internet Connection", "Device seems to have lost internet connection." +
                    " Please ensure the tablet has internet connectivity.", "OK");
                }
    
                await Task.Delay(5000);
            }
        }`
    
  • JohnHardmanJohnHardman GBUniversity mod

    @BoomShankar said:
    Following instructions from the above members. Here's what I did so that the app asynchronously keeps checking if the internet is present every five seconds.

    Won't work in mainland China whilst the Great Firewall blocks access to Google.
    If using mobile data, will be clocking up charges.
    Not being done on a worker thread, so will cause lag on UI thread.
    Are you really sure you want to do DisplayAlert every 5 seconds (assuming user presses OK) if connecting to URL fails?

  • BoomShankarBoomShankar USMember ✭✭

    @JohnHardman I removed chunks of code which was specific to the logic I was working with. But this shortened version would do the trick and good call on the DisplayAlert, it shouldn't be there if not handled properly.

    Also, Google could be replaced with something similar over there.

Sign In or Register to comment.