8

As getActiveNetworkInfo is deprecated now in Android according to official document, I am using below implementation to get callback about Internet connectivity.

private val connectivityManager: ConnectivityManager by lazy {
   getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}

private val builder: NetworkRequest.Builder by lazy {
   NetworkRequest.Builder()
}

private val networkCallback: NetworkCallback by lazy {
   object : NetworkCallback() {
      override fun onAvailable(network: Network?) {
          println("Connection is online")
      }

      override fun onLost(network: Network?) {
          println("Connection is offline")
      }
   }
}

override fun onResume() {
   super.onResume()
   connectivityManager.registerNetworkCallback(builder.build(), networkCallback)
}

override fun onPause() {
   super.onPause()
   connectivityManager.unregisterNetworkCallback(networkCallback)
}

It works well when this callback register when connection is online, but it does not work properly when internet is off and then we register callback. To test such scenarion, I kept my app closed. Then keep internet connection off and then open app.

Do we have any way to know even app is opening? If so, please help to share it. Thanks.

Jigar
  • 421
  • 2
  • 11
  • Do registerNetworkCallback(...) in onStart() and unregisterNetworkCallback(...) in onStop() – VVB Jan 30 '20 at 09:33
  • Also, override onUnavailable () to confirm whether register/unregister are in place. – VVB Jan 30 '20 at 09:54

1 Answers1

1

According to your question, I would suggest reading this part of the Android documentation. You are using onPause() and onResume(), you should try out onStop().

But I think you have to call the super.onPause() after your logic connectivityManager.unregisterNetworkCallback(networkCallback) because it will pause the app before your method is even called.

LKSoftware
  • 49
  • 3
  • I have added sample code here, but the issue is when internet connection off and then user opens app, at that time not getting connection status. – Jigar Jan 30 '20 at 08:46
  • You should check if your connectivity manager is still there, same goes for the onResume() try putting the super.onResume() below your logic. – LKSoftware Jan 30 '20 at 09:02
  • You could try checking on resum if the connecitivty state is available, if not try to register the network callback again, if this doesn't help try to get a new instance of the ConnectivityManager. – LKSoftware Jan 31 '20 at 11:05