Check Network Availability

Apps that communicates with web services needs to check network availability before calling them. Failing do so may break the app when there are no network present. You can use following code segment/method to check the network availability.

If network available then TRUE returned from the method.

boolean networkStatus = getNetworkStatus();
		call the web service here!
		Toast.makeText(IncidentFormActivity.this,"Network Error!", 2000).show();

Method (make sure class extended to Activity).

protected boolean getNetworkStatus() {
	ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    if (cm.getActiveNetworkInfo() != null
	            && cm.getActiveNetworkInfo().isAvailable()
	            && cm.getActiveNetworkInfo().isConnected()) {
	        return true;
	    } else {
	        Log.v(TAG, "Internet Connection Not Present");
	        return false;

sometimes cm.getActiveNetworkInfo() returns NULL when the network is not present so better to do a null check in the method as I wrote above.

Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.

Leave a Reply