2

Below is the piece of Android code which works fine to check if network is connected or not.

public static boolean isNetworkAvailable(Context context) 
{
    ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}

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

But having an active network interface doesn't guarantee that a particular networked service is available.

A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google

Common scenario:

  1. Android device connected to a Wi-Fi, which turns out to be a private network. So isNetworkAvailable will return that network is connected, but could not be connected to any other service
  2. Some times the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access Google/Yahoo.

One way is to check if "isNetworkAvailable" function returns TRUE, then run following code

HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);

   HttpEntity entity = response.getEntity();


     if (entity != null)
      {
         result = EntityUtils.toString(entity);
      }

   }
 catch (SocketException e)
  {
     return "Socket Exceptiopn:" + e.toString();
  }
 catch (Exception e)
  {
     return "General Execption:" + e.toString();
  }

But I think this is not an good way because it may consume lot of time

So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Rohit
  • 6,941
  • 17
  • 58
  • 102
  • this is a good way to check, but you can write in organised way in given answer with respect to yours question. – Jitesh Upadhyay Jan 10 '14 at 09:18
  • 1
    i will suggest you to have a look on this http://stackoverflow.com/questions/8919083/checking-host-reachability-availability-in-android –  Jan 10 '14 at 09:30

3 Answers3

2

check this code... it worked for me :)

public static void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)

                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://m.google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

}

Then, I define the handler:

Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }

    }
};

and launch the test:

isNetworkAvailable(h,2000); // get the answser within 2000 ms

Code from Gilbou https://stackoverflow.com/a/5803489/2603719

I hope i can Help you

Community
  • 1
  • 1
elHomer
  • 48
  • 2
  • 10
  • Thanks! But is it more efficient (in terms of time taken) than my code ? – Rohit Jan 10 '14 at 09:43
  • 1
    You can set the timer also down. `@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Handler h = new Handler() { // // @Override public void handleMessage(Message msg) { if (msg.what != 1) { //NO INTERNET} else {// INTERNET } } }; isNetworkAvailable(h, 2000);}´ – elHomer Jan 10 '14 at 09:45
  • this seems better approach! – Rohit Jan 10 '14 at 09:48
  • Do you have any idea about the lifetime of this thread? it will run forever.put a log inside it and check it. – Mehul Joisar Jan 10 '14 at 09:59
  • HttpGet - I got this error, "cannot resolve HttpGet? – Faris Muhammed Apr 27 '18 at 17:45
1

Issue #1:
Android device connected to a Wi-Fi, which turns out to be a private network.
So isNetworkAvailable will return that network is connected, but could not be connected to any other service.

Issue #2:
Sometimes the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access google/yahoo.

I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.

Ultimately, you will need to Monitor the change in Network connection,

Step 1:

Just register a BroadcastReceiver for following action

<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

Step 2:

when you get callback on onReceive(Context context,Intent intent) method ,check for connectivity status.

i.e: boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);

//apart from EXTRA_NO_CONNECTIVITY, there are other parameters also which will be useful to monitor

Reference:

Examples:

Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android

Android-getting-notified-of-connectivity-changes

Github: Example for network-detect-notify

Android Docs:

Connectivity Monitoring

Connectivity Manager

I hope it will be helpful !!

S1LENT WARRIOR
  • 11,704
  • 4
  • 46
  • 60
Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57
-1

Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.

        boolean flag=false;
        ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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)
                    {
                        flag=true;

                    }

        }
        if(flag==true)
        {
             Log.e("TAG","Internet Is Connected");
        }
        else
        {
              Log.e("TAG","Internet Is Not Connected");
        }
Prashant Bhoir
  • 900
  • 6
  • 8
  • Not only checking the connectivity but also checking the reachability is necessary. For instance, what if ip address is invalid or dns server is down? – Daniel Park Apr 13 '21 at 13:07