How do you check the internet connection in android? [duplicate]

I want to check the internet connectivity in each activity. If it is lost a message should be displayed.

Can any one guide me how to achieve this?


Solution 1:

Only one connection can be active at any one point. So a simpler answer is:

final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
    // notify user you are online
} else {
    // notify user you are not online
} 

It also caters for any new type of network such as ConnectivityManager#TYPE_WIMAX


Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Solution 2:

You can use the ConnectivityManager to check the network state.

ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED 
    || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) {

    // notify user you are online

}
else if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED 
    || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {

    // notify user you are not online
}

Note that the constants ConnectivityManager.TYPE_MOBILE and ConnectivityManager.TYPE_WIFI represent connection types and these two values are not exhaustive. See here for an exhaustive list.


Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />