The following is the code used to check network connectivity
package com.app.helper;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkHelper {
/*It checks whether network connection is available or not.
* */
public static boolean isOnline(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting() && canHit()) {
Log.d(UMobileApp.TAG,"In NetworkHelper :connection available");
return true;
}
return false;
}
/* It checks whether connection to the URL can be established or not.
* Also a timout is set to 3000ms. */
public static boolean canHit() {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (Exception e) {
Log.e(UMobileApp.TAG,"Exception In NetworkHelper :"+e.getMessage());
e.printStackTrace();
return false;
}
}
/* To exit if the network connection is not available.*/
public static void exitIfOffline(Activity act) {
if (!isOnline(act.getApplicationContext())) {
MessageBox.alert(act.getResources().getString(R.string.no_connection_found ), act, true);
}
}
}
Here I am checking the network connectivity through the static method isOnline. Now the problem is using the above approach, the network works fine for api level 9 and below, but otherwise it returns false as the boolean value. Spent almost 3 hours to detect this anomaly. Do we really need to check for network connection based on api levels or is there a generic method which returns the same value for all api levels