Android Check for Wi-Fi but No Internet

I am writing a program where I need to check three states: 1. If I do not have Wi-Fi, 2. If I have Wi-Fi, but do not have an Internet connection (for example, if I turn on my router, but unplug the Ethernet cable) and 3. If I have WiFi and internet connection. Then I would change the color of the icon in my application to represent one of these states (red, yellow, or green). Condition 2 is currently not working, at any time when I disconnect the cable from my router for testing, the icon color changes from green to red.

public static void doPing(Context context) { String googleUrl = "https://www.google.com"; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); HttpClient client = new DefaultHttpClient(httpParameters); if (L) Log.i(TAG, "Calling: " + url ); HttpGet getGoogle = getHttpGet(googleUrl); HttpResponse responseGoogle = client.execute(getGoogle); if (responseGoogle != null){ connectionIconView.setIcon(R.drawable.green_wifi); } else if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null){ connectionIconView.setIcon(R.drawable.yellow_wifi); } else { connectionIconView.setIcon(R.drawable.red_wifi); } } catch(Exception e) { if (L) Log.e(TAG, "Error during HTTP call"); e.printStackTrace(); } 
+7
android wifi connection
source share
1 answer

Check if wifi is available like this

function 1

 private boolean isWifiAvailable() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return wifi.isConnected(); } 

After that, check it if the Internet is available.

function 2

  public static boolean isInternetAccessible(Context context) { if (isWifiAvailable()) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1500); urlc.connect(); return (urlc.getResponseCode() == 200); } catch (IOException e) { Log.e(LOG_TAG, "Couldn't check internet connection", e); } } else { Log.d(LOG_TAG, "Internet not available!"); } return false; } 

Conditions

  • If function 1 returns false -> change color to RED
  • If function 1 returns true and function 2 returns false -> change color to YELLOW
  • If both functions return true -> change color in GREEN
+14
source share

All Articles