I've already read many other answers posted on the internet but they are not exactly what I'm looking for, I know how to check if the device is connected/disconnected
to the internet/mobile
data what I am trying to do is check if data is transferable through that network or not, you might be connected to a network but might not be able to transfer data through that network.
here is what I'm doing now
val listener = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
isActiveNetwork()
}
override fun onUnavailable() {
super.onUnavailable()
}
override fun onLost(network: Network) {
super.onLost(network)
// no internet
}
}
(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).registerNetworkCallback(NetworkRequest.Builder().build(), listener )
the isActiveNetwork
method is used to check if the internet connection is active or not
private fun isActiveNetwork(){
try {
if(InetAddress.getByName("www.google.com").isReachable(5000)){
//active
}
else{
// not active
}
} catch (e: Exception) {
//not active
}
}
the problem is this method will check if the internet connection is active once and that's all, I've tried to do this
private fun isActiveNetwork(){
try {
if(InetAddress.getByName("www.google.com").isReachable(5000)){
//active
}
else{
isActiveNetwork()
}
} catch (e: Exception) {
isActiveNetwork()
}
}
to try and keep checking every 5 seconds to see if the internet connection is active, but that caused my app to crash because of StackOverflow
.... any suggestions?