Reputation: 1437
How to check for Internet access in Android?
Why does it always return true
?
I am sure I am not connected to Internet. Why does it return true
?
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isAvailable() &&
cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.v("TAG", "Internet Connection Not Present");
return false;
}
}
Upvotes: 1
Views: 1677
Reputation: 5199
You could try testing to figure out which connection is seen as active:
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
if (netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) {
Log.v("TAG", "Mobile Internet connected");
return true;
}
if (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()) {
Log.v("TAG", "Wifi Internet connected");
return true;
}
return false;
}
Edit: On the emulator, it will always show mobile connected regardless of your computer's Internet connection. Use F8 to switch it off, as per this answer:
https://stackoverflow.com/a/2937915/560092
Upvotes: 3
Reputation: 7882
The method you are using doesn't always work correctly. Some times it will return true even if you are connected to a wifi network (but that network isn't actually connected to internet), etc. The other alternative is
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
if ((netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) || (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting())) {
return true;
}
return false;
}
Upvotes: 0
Reputation: 481
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean isAvailable = activeNetworkInfo != null && activeNetworkInfo.isConnected();
if(!isAvailable) {
Toast.makeText(this,"Unable to connect", Toast.LENGTH_SHORT).show();
}
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Upvotes: 0