How to check Wifi is connected, but no Internet access in Android

Smit Patel picture Smit Patel · May 16, 2013 · Viewed 12.7k times · Source

I would like to know why wifi is connected but there is no internet access in Android. How can i check it? My code is:

ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo nf=cn.getActiveNetworkInfo();

 if(nf != null && nf.isConnected() )
         {
            Flag2=false;
            Log.e("network--------", "1--------------");

            if (cn.getActiveNetworkInfo().isConnectedOrConnecting())
            {Log.e("network--------", "11111111111111--------------");
             }
            else
            {Log.e("network--------", "2222222222222--------------");
            }
        }

 else 
         {
            Log.e("network--------", "2--------------");
 }

Answer

Oli picture Oli · May 16, 2013

You could try something like this:

public void checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        if (InetAddress.getByName("www.xy.com").isReachable(timeout))
        {  
         // host reachable  
        }
         else
         {    
         // host not reachable  
         }  
    }
    return;
}

dont forget the access

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

Hope it will work :)