how to check internet connection in android programmatically


If the device is in airplane mode (or presumably in other situations where there's no available network), cm.getActiveNetworkInfo() will be null, so you need to add a null check.
Modified (Eddie's solution) below:
public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); }
Also add the following permission to the AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use netInfo.isConnected() rather than netInfo.isConnectedOrConnecting. I guess this is up to the individual use-case however.
Found at and modified (!) from this link :
In your manifest file add at least:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You probably already have the INTERNET permission if you are accessing it. Then a boolean function that allows to test for connectivity is:
private boolean checkInternetConnection() { ConnectivityManager cm = (ConnectivityManager) 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; } }

No comments:

Post a Comment

Popular Posts