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(); if(networkStatus){ call the web service here! } else{ 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.
Subscribe to our mailing list
Subscribe to our mailing list and receive a free udpates
Leave a Reply