Checking internet connection on android
Sometimes the active connection is not first in the list, or is inactive or in an error state. This is how I would do it:
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
[EDIT 1] Don't forget to add this permission in the application manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Does this help you?
Emmanuel
Is better:
if (conMgr != null) {
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected())
ret = false;
if (!i.isAvailable())
ret = false;
}
if (i == null)
ret = false;
} else
ret = false;
with the other form, if "Network i" is equal null then, check after for !i.isConnected()
must fail (i is null).
The short answer:
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}