HOWTO: detecting internet

Even the Android SDK and stackoverflow don’t have this right. They only do Wifi or Mobile. But not 4G/WiMax or Bluetooth tether.

So here it is for you guys. Please note if the user does NOT have a dataplan, his phone may still report a valid internet connection - but it is ONLY to his phone provider to try sell him a data plan!

And obviously setProgressMessage() is some other code of mine…


		    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		    for (NetworkInfo ni : netInfo) {
		        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
		            if (ni.isConnected())
		            {
		                haveConnectedWifi = true;
		            	setProgressMessage("Using WiFi");
		            }
		        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
		            if (ni.isConnected())
		            {
		                haveConnectedMobile = true;
		                setProgressMessage("Using phone network");
		            }
		        if (ni.getTypeName().equalsIgnoreCase("WIMAX"))
		            if (ni.isConnected())
		            {
		                haveConnectedMobile = true;
		                setProgressMessage("Using WIMAX");
		            }
		        if (ni.getTypeName().equalsIgnoreCase("ETHERNET"))
		            if (ni.isConnected())
		            {
		            	haveConnectedEth = true;
		                setProgressMessage("Using Ethernet");
		            }
		        if (ni.getTypeName().equalsIgnoreCase("BLUETOOTH"))
		            if (ni.isConnected())
		            {
		            	haveConnectedBluetooth = true;
		                setProgressMessage("Using Bluetooth");
		            }

		    }
		    if (haveConnectedWifi | haveConnectedMobile | haveConnectedBluetooth | haveConnectedEth)
... etc

This is the one I use:

	/**
	 * Returns true if there is a network connection available.
	 * Requires: android.permission.ACCESS_NETWORK_STATE
	 * @return true if there is a network connection available, false otherwise.
	 */
	
	public static boolean isNetworkAvailable(Context context) {
	    ConnectivityManager cm = 
	    		(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    return netInfo != null && netInfo.isConnected();
	}