Android: Check if Internet connection is available

If the application wants to check if the Internet connection is available, we must add the application permission: ACCESS_NETWORK_STATE. I already wrote how to set the Application permissions.

The Android API provided two classes:
ConnectivityManager – Class that answers queries about the state of network connectivity
NetrowkInfo – Describes the status of a network interface

We need to import both classes

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

and here is the method which returns true if the Internet connection is available and false if the Internet connection is not available.

/**
 * Check if Internet connection is available
 * @return boolean true-available; false-not available
 */
private boolean isNetworkAvailable() {
  ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Leave a Reply