-3

what will be the best solution for the case stated below whether the user has active internet connection or not( by active i mean that user can open any web URl).

  1. By making http request to google.com and check the respose code, or
HttpURLConnection urlc = (HttpURLConnection)
                        (new URL("http://clients3.google.com/generate_204")
                                .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.connect();
                Log.d("reqcode",""+urlc.getResponseCode());
                return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
  1. by making a request to the server which i am using.

and which is best in terms of performance.

Aman Verma
  • 3,155
  • 7
  • 30
  • 60
  • 1
    Probably best to look at the Android documentation before posting here. [Determining and Monitoring the Connectivity Status](https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html) – Richard Le Mesurier Aug 25 '16 at 10:56
  • Possible duplicate of [How to check internet access on Android? InetAddress never times out](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out) – Shaishav Jogani Aug 25 '16 at 11:37

3 Answers3

1

Use a method like this:

private boolean isNetworkAvailable() {
       ConnectivityManager connectivityManager
                 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
       return activeNetworkInfo != null && activeNetworkInfo.isConnected();
     }

Then just:

if(isNetworkAvailable()) {
    //Do what you want with internet
} else {
    //Do something wothout internet
}

You also need to add this in your manifest file:

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

Anyway: Question

Community
  • 1
  • 1
Koss
  • 124
  • 2
  • 13
0

I use below method to check whether, user has active internet connection by either Mobile data or by wi-fi.

public static boolean isInternetConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }  
        }
        return false;
    }

and add permission in manifest file.

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

There is no way to determine whether user has active connection or not. The method you suggested in your question will lead you into long waiting period if user has no active connection and throw SocketTimeOutException after some time.

So, if you want to check whether user has internet connection or not, then only check it has enable wi-fi and/or data connection, and assume data pack is on.

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
  • not working, i want to know if the device has an active connection( not just connected to wifi) i have implemented it it always return true except when my wifi is off. – Aman Verma Aug 25 '16 at 12:18
  • yeah thats the things, i used the method stated in my question and i have to wait for about 20 seconds to get the response code. although there is another method which uses socket and it is quite fast but not working on many device. android device uses the mentioned code for checking active connection – Aman Verma Aug 25 '16 at 22:33
  • @AmanVerma If my answer helps you then I would appreciate if you up-vote/Accept it :-) – Shaishav Jogani Sep 07 '16 at 10:28
  • the solution you proposed is not working still... I want to know if the device has an active internet connection or not, your solution is working if the device is on airplane mode or wi-fi is Off. – Aman Verma Sep 07 '16 at 16:02
0

Don't ping websites to check internet connectivity. It is a very bad practice since the site can block your app permanently or just the one server might be down.

Instead use a BroadCastReceiver to to listen for internet connectivity Intent. Extend your class from BradcastReceiver and within your onReceive use

private boolean isConnectedToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }
      }
      return false;
}

to check connectivity status.

You may also want to register and unregister the receiver in your Activity's onResume() and onPause() method with

registerReceiver(networkChangeListener, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
...
unregisterReceiver(networkChangeListener);
Abbas
  • 3,529
  • 5
  • 36
  • 64