2

I'm looking for a solution to detect Network Events in my Android project, specifically the Connected and Disconnected Events.

With older Android versions, we were able to listen such events from Broadcast receivers. Work Manager has some constraints to work with but I don't think it fits the mold here because the library doesn't expose the state of the constraints (Network States in this case). Even if it does, 15 minutes limit is gonna be a pain, if the user toggles the internet multiple times during 15 minutes.

Is Job Scheduler good for this situation? Can it detect both Network Connected and Disconnected Events?

Halil Ozel
  • 2,482
  • 3
  • 17
  • 32
  • 1
    In order to avoid an [XY Problem](https://xyproblem.info/), can you share your actual problem and what you are trying to do with this information? – ianhanniballake Feb 05 '23 at 23:52
  • @ianhanniballake I'm doing realtime syncing with precise logging, in which I need to know both the connected (to sync) and disconnected (to log) events. – Affection77 Feb 06 '23 at 04:30
  • 1
    Realtime syncing of _what_? Explain what that means and how you are doing that. Please update your question, rather than using comments for this information. – ianhanniballake Feb 06 '23 at 05:19
  • Please check the answers posted. ConnectivityManager can help in this case – Vartika Sharma Feb 08 '23 at 21:00

1 Answers1

0

For this situation, ConnectivityManager system service is good to detect frequent network changes

  class NetworkStateManagement(val context:Context)
  :ConnectivityManager.NetworkCallbacks() {
  private lateinit var connectivityManager

  init {
   connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) 
  as ConnectivityManager
 }

override fun onAvailable(network : Network?) {
   super.onAvailable(network)
   Log.d(TAG, "onAvailable() called: Connected to network")
  }

@Override fun onLost(network : Network?) {
    super.onLost(network);
    Log.e(TAG, "onLost() called: Lost network connection");
}

/**
 * Registers the Network-Request callback
 * (Note: Register only once to prevent duplicate callbacks)
 */
open fun registerNetworkCallbackEvents() {
    Log.d(TAG, "registerNetworkCallbackEvents() called");
    mConnectivityManager.registerNetworkCallback(mNetworkRequest, context);
}