An Android device can be connected to the Internet via interfaces like 3g/4g network or via Wifi/Bluetooth etc. Even if one of them connected to the internet, the Android app can connect to internet through that interface automatically.


The following code snippet shows how to check if an Android device is connected to the Internet.

package com.codercrunch.picwords.gcm;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Check if the device has internet connectivity.
 */
public class InternetConnectionDetector {

private Context _context;

public InternetConnectionDetector(Context context) {
    this._context = context;
}

/**
 * Check all the network connectors
 * **/
public boolean canConnectToInternet() {

    // get handle to connectivity service
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {

       // get all network info
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
           // loop through
           for (int i = 0; i < info.length; i++)

             // check if any interface is connected
             if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                 return true;
              }

           }
      return false; // no interface is connected
    }
}