I am developing an app in which I need to check if an internet connection is available or not. The code I have written seems to handle all cases but it is not working in my emulator. My code:
public boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
The problem is that it is never returning false
whether the internet connection is available or not, both in a device and in my emulator. But it is working well if the device is connected with wifi connection. What problem with that snippet?