0

I am trying to build an app ,where in I first need to check if internet connection is available or not,even if it is connected to the WIFI router which does not have a internet connectivity?From sources I came to know ,in order to check this I need to ping the site for e.g.(www.google.com).Please help me with the exact snippet I need to include? Thanks

Radhika Obhan
  • 19
  • 1
  • 5
  • https://stackoverflow.com/a/4009133/5552022 – Omar Aflak Jun 07 '17 at 18:26
  • i found a better solution for you check it out https://stackoverflow.com/questions/8535092/how-to-check-that-internet-on-local-wifi-is-available-or-not?rq=1 – nasser Jun 07 '17 at 18:28
  • Possible duplicate of [how to check that internet on local wifi is available or not?](https://stackoverflow.com/questions/8535092/how-to-check-that-internet-on-local-wifi-is-available-or-not) – Abhishek Jain Jun 07 '17 at 18:42
  • @AbhishekJain i am getting an error on isNetworkAvailable()? – Radhika Obhan Jun 07 '17 at 18:44

2 Answers2

0

this method work fine for me

 public final boolean isInternetOn() {
        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            // if connected with internet
            // Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

            //  Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }
nasser
  • 122
  • 2
  • 8
0

Try this:

 public static boolean hasInternet(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}
Jonathan Aste
  • 1,714
  • 1
  • 12
  • 19