How should I handle “No internet connection” with Retrofit on Android

前端 未结 8 917
一个人的身影
一个人的身影 2020-12-02 03:55

I\'d like to handle situations when there is no internet connection. Usually I\'d run:

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemSer         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 05:01

    With Retrofit 2, we use an OkHttp Interceptor implementation to check for network connectivity ahead of sending the request. If no network, throw an exception as appropriate.

    This allows one to specifically handle network connectivity issues before hitting Retrofit.

    import java.io.IOException;
    
    import okhttp3.Interceptor;
    import okhttp3.Response;
    import io.reactivex.Observable
    
    public class ConnectivityInterceptor implements Interceptor {
    
        private boolean isNetworkActive;
    
        public ConnectivityInterceptor(Observable isNetworkActive) {
           isNetworkActive.subscribe(
                   _isNetworkActive -> this.isNetworkActive = _isNetworkActive,
                   _error -> Log.e("NetworkActive error " + _error.getMessage()));
        }
    
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            if (!isNetworkActive) {
                throw new NoConnectivityException();
            }
            else {
                Response response = chain.proceed(chain.request());
                return response;
            }
        }
    }
    
    public class NoConnectivityException extends IOException {
    
        @Override
        public String getMessage() {
            return "No network available, please check your WiFi or Data connection";
        }
    }
    

提交回复
热议问题