Android retrofit 2 have internet check? (some kind of method) just every time to check in such a way as something not very (((

  ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 
  • one
    Why do you need this check? It may be such a situation that when checking the Internet will be, and already when working directly with the network - no. - s8am

1 answer 1

For synchronous requests.

 Response<T> execute() throws IOException 

That is, you need to catch IOException

 try{ syncCall.execute(); } catch (IOException e){ обработка эксепшена } 

For asynchronous, you must override the onFailure method.

 void onFailure(Call<T> call, Throwable t) 

Something like this

 asyncCall.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { } @Override public void onFailure(Call<T> call, Throwable t) { Обработка ошибки } }); 
  • onFailure t.getMessage () "Failed to connect to" shows an error when there is no Internet and when the server is not available, so it is not clear how to distinguish this error - Suleymanovtat
  • 2
    @Suleymanovtat if it is really critical for you to so subtly understand the cause of server inaccessibility for the application, then you can insert a helper call onFailure, which will check the details - rjhdby