Created
July 19, 2019 12:56
-
-
Save arildojr7/67e2da97bd61c27fdc66ca1b3f621dbd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NoConnectionInterceptor(private val context: Context) : Interceptor { | |
override fun intercept(chain: Interceptor.Chain): Response { | |
return if (!isConnectionOn()) { | |
throw Exception("CELULAR CONECTADO") | |
} else if (!isInternetAvailable()) { | |
throw Exception("MAS SEM INTERNET") | |
} else { | |
Log.e(">>>> ", "Deu Bom") | |
chain.proceed(chain.request()) | |
} | |
} | |
private fun isInternetAvailable(): Boolean { | |
return try { | |
val timeoutMs = 1500 | |
val sock = Socket() | |
val sockaddr = InetSocketAddress("8.8.8.8", 53) | |
sock.connect(sockaddr, timeoutMs) | |
sock.close() | |
true | |
} catch (e: IOException) { | |
false | |
} | |
} | |
private fun isConnectionOn(): Boolean { | |
val connectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as | |
ConnectivityManager | |
return if (android.os.Build.VERSION.SDK_INT >= | |
android.os.Build.VERSION_CODES.M) { | |
postAndroidMInternetCheck(connectivityManager) | |
} else { | |
preAndroidMInternetCheck(connectivityManager) | |
} | |
} | |
private fun preAndroidMInternetCheck( | |
connectivityManager: ConnectivityManager): Boolean { | |
val activeNetwork = connectivityManager.activeNetworkInfo | |
if (activeNetwork != null) { | |
return (activeNetwork.type == ConnectivityManager.TYPE_WIFI || | |
activeNetwork.type == ConnectivityManager.TYPE_MOBILE) | |
} | |
return false | |
} | |
@TargetApi(23) | |
private fun postAndroidMInternetCheck( | |
connectivityManager: ConnectivityManager): Boolean { | |
val network = connectivityManager.activeNetwork | |
val connection = | |
connectivityManager.getNetworkCapabilities(network) | |
return connection != null && ( | |
connection.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || | |
connection.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment