java – The best approach for checking the Internet connection in a network application


I would like to know the best way to implement an Internet connection check in a network application. I use Retrofit2 , every n seconds I need to poll the server.

implement okhttp3.Interceptor

    public Response intercept(Chain chain) throws IOException {
    if (!NetworkUtils.isNetworkAvailable(mContext)) {
            throw new NetworkException();

when retrofit2. Callback<T> request to the server, retrofit2. Callback<T> in the onFailure(Call<MyModel> call, Throwable t) callback method onFailure(Call<MyModel> call, Throwable t) check if (t instanceof NetworkException) then once I if (t instanceof NetworkException) message that there is no Internet connection.

But I am confused by the fact that every time the server is polled, I need to perform the isNetworkAvailable check, in which to "pull" ConnectivityManager getActiveNetworkInfo() , check instanceof in onFailure() …. so I'm not sure if this is the best approach.

The approach with the definition of a broadcastreceiver that listens for network status change events seems to me to be more optimal, event-driven, but it is considered deprecated. Therefore, I wanted to find out how to implement the Internet connection check in the most optimal way.


The best solution is to stop reinventing the wheel and parts of the operating system. The user himself knows what he has. Just do your job, for what the application is written.

If there is a network, this does not mean that your host is available, for example, due to network congestion. Just write the message "I can't connect" and that's it. One less permision to a heap.

If you are polling some resource with a high frequency, then it 's time to change the slave, be sure to correctly handle errors and tell the user. You can even make a setting like "In case of problems with the update: stop / continue for 1 minute / continue always". How and when the network appears, what needs to be done – IT'S NOT YOUR BUSINESS , the user and his OS will decide it themselves, and such bicycles only lead to the fact that it will be necessary to distort the connections / wiring / go out and go in.

Scroll to Top