java – How to prevent the use of the application without the Internet?


I have requests all the time, and if you turn off the Internet and go into the application, it always crashes, and it is costly to install checks everywhere.

Is there a one-size-fits-all solution?


It is possible in different ways:

  1. Check the presence of the Internet at the entrance to the application, i.e. when starting the main Activity . And do not start k-l tasks until a successful check.
  2. Make an Internet activity checker. Run on the current main and this one. If there is Internet, then launch the current home page. Otherwise, exit the application.
  3. Wrap all current requests to the network in a class that checks the presence of Internet before starting the task. If it is, continue, otherwise, close the application.

You can check the presence of a connection to the network (not the fact that there is the Internet itself), according to en-SO, as follows :

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();

You also need to add a special. permission in AndroidManifest.xml :

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

Another point: if you need to check the fact of being connected to the Internet (and not подключено-или-подключается ), then you need to use netInfo.isConnected() instead of netInfo.isConnectedOrConnecting() .

Check whether the Internet is, as such, may be here because :

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName(""); //можно заменить на к-л другой сайт

        if (ipAddr.equals("")) {
            return false;
        } else {
            return true;

    } catch (Exception e) {
        return false;


And don't forget about all the necessary permissions in the manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Scroll to Top