androidandroid-activitynetwork-state

How do you check the internet connection in android?


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

  • 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" />