Skip to content

Instantly share code, notes, and snippets.

@adityaladwa
Last active November 20, 2020 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adityaladwa/04a3246b5a6b33c5e271492a91d0c4ca to your computer and use it in GitHub Desktop.
Save adityaladwa/04a3246b5a6b33c5e271492a91d0c4ca to your computer and use it in GitHub Desktop.
An okhttp interceptor to check internet connection before making a http request
class NetworkInterceptor(context: Context) : Interceptor {
private val mApplicationContext: Context = context.applicationContext
private val isConnected: Boolean
get() {
val cm = mApplicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnectedOrConnecting
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
if (!isConnected) {
throw NoNetworkException()
}
return chain.proceed(originalRequest)
}
class NoNetworkException internal constructor() : RuntimeException("Please check Network Connection")
}
@raosuj
Copy link

raosuj commented Aug 30, 2018

RuntimeException is causing a crash for me, fixed by using an IOException

@ma-za-kpe
Copy link

its still causes crush even with ioexception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment