android check for internet connection code example
Example 1: Android check internet
public class InternetConnection {
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
}
Example 2: how-to-check-internet-connection-in-android
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else {
return true;
}
}
Example 3: Android check internet
class NetWorkInfoUtility {
public boolean isWifiEnable() {
return isWifiEnable;
}
public void setIsWifiEnable(boolean isWifiEnable) {
this.isWifiEnable = isWifiEnable;
}
public boolean isMobileNetworkAvailable() {
return isMobileNetworkAvailable;
}
public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}
private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;
public boolean isNetWorkAvailableNow(Context context) {
boolean isNetworkAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
if (isWifiEnable() || isMobileNetworkAvailable()) {
if (isOnline())
isNetworkAvailable = true;
}
return isNetworkAvailable;
}
public boolean isOnline() {
long t = Calendar.getInstance().getTimeInMillis();
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
long t2 = Calendar.getInstance().getTimeInMillis();
Log.i("NetWork check Time", (t2 - t) + "");
}
return false;
}
}