Android: Intercept on no internet connection

I have blog compare iOS and Android networking previously. iOS with Alamofire library automatically provide capability to detect when data connection is not on. However Android OkHttp library does provide that by default.

So in this blog, I’ll show how to setup no internet connection detection naturally in OkHttp, which only needs to be done once in your code, and used by all network call.

I’ll show you how it is done in a reverse order.

Setup the interceptor in the OkHttpClient

As show in my previous blog, in Android, we’ll need to have OkHttpClient for our network call.

OkHttp provide us a way to intercept the network call through it’s interceptor plugin into the OkHttpClient. We’ll just need to create our interceptor for any specific function we want to do, in this case, which is `check for no network`

To make OkHttpClient no network aware, we’ll provide it with a NoConnectionInterceptor object.

OkHttpClient.Builder()
.addInterceptor(NoConnectionInterceptor(context))
.build()

Note: In the example code, I use Dagger 2 to inject the OkHttpClient to make the entire application more structured and decoupled. If you like to learn about Dagger 2, check out…

--

--