Affection77
Affection77

Reputation: 69

Is there a way to detect Network Connected and Disconnected events in Android 13?

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?

Upvotes: 2

Views: 244

Answers (1)

Vartika Sharma
Vartika Sharma

Reputation: 134

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");
   connectivityManager.registerNetworkCallback(mNetworkRequest, context);
}

Upvotes: 0

Related Questions