We use the Android ConnectivityManager
to listen for internet connection changes inside our app as follows.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
ConnectionStateMonitor().enable(this)
}
class ConnectionStateMonitor : NetworkCallback() {
private val networkRequest: NetworkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build()
fun enable(context: Context) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.registerNetworkCallback(networkRequest, this)
}
override fun onAvailable(network: Network) {
Log.i(TAG, "onAvailable ")
}
override fun onLost(network: Network?) {
super.onLost(network)
Log.i(TAG, "onLost ")
}
}
}
This implementation is working well except for two issues we've encountered
If we connect to the internet by using both wifi and mobile data and turn off wifi sometimes the
onLost()
callback is fired followed byonAvailable()
, as expected, but in other instances onlyonLost()
is fired which is incorrect.If we don't have internet connection and open the app
onLost()
is not fired, however if we have internet connection and open the apponAvailable()
is fired.
Any help, suggestions, workarounds or another approaches to detect internet connection changes reliably would really be appreciated.
Tested on Xioami A2 (Android 9), OnePlus (Android 9)
DEMO project
https://github.com/PhanVanLinh/AndroidNetworkChangeReceiver