Android – check Internet connection

By -
Problem: How To check whether the device has network connection or not?
Solution:

public static boolean checkNetworkConnection(Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final android.net.NetworkInfo wifi = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		final android.net.NetworkInfo mobile = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifi.isAvailable() || mobile.isAvailable())
			return true;
		else
			return false;
	}

Update:
This will work for both Emulator & Device. I got this helpful information from this SO answer.

connected = (connMgr.getActiveNetworkInfo() != null &&
connMgr.getActiveNetworkInfo().isAvailable() &&
connMgr.getActiveNetworkInfo().isConnected()   )

Note the use of isAvailable – without this isConnected can return TRUE even when WIFI is disabled.

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

Loading Facebook Comments ...
Loading Disqus Comments ...