Avoid useless service restart
Restart service with networkCallback only when Internet is available again.
This commit is contained in:
parent
ec7e27b3a3
commit
254a776244
|
@ -15,7 +15,7 @@ class RestartNetworkCallback(val context: Context) : ConnectivityManager.Network
|
|||
override fun onAvailable(network: Network) {
|
||||
Log.d(TAG, "Network is CONNECTED")
|
||||
if (FailureHandler.hasFailed(twice = true, orNeverStart = false)) {
|
||||
Log.d(TAG, "networkCallback: restarting worker")
|
||||
Log.d(TAG, "Available: restarting worker")
|
||||
RestartWorker.run(context, delay = 0)
|
||||
}
|
||||
}
|
||||
|
@ -24,14 +24,23 @@ class RestartNetworkCallback(val context: Context) : ConnectivityManager.Network
|
|||
network: Network,
|
||||
networkCapabilities: NetworkCapabilities
|
||||
) {
|
||||
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
|
||||
if (!hasInternet) {
|
||||
hasInternet = true
|
||||
Log.d(TAG, "Network Capabilities changed")
|
||||
if (FailureHandler.hasFailed(twice = true, orNeverStart = false)) {
|
||||
Log.d(TAG, "networkCallback: restarting worker")
|
||||
Log.d(TAG, "Internet Cap: restarting worker")
|
||||
RestartWorker.run(context, delay = 0)
|
||||
} // else, it retries in max 2sec
|
||||
}
|
||||
} else {
|
||||
hasInternet = false
|
||||
}
|
||||
}
|
||||
|
||||
fun register() {
|
||||
if (!registered) {
|
||||
registered = true
|
||||
connectivityManager?.let {
|
||||
Log.d(TAG, "ConnectivityManager already registered")
|
||||
} ?: run {
|
||||
|
@ -47,10 +56,18 @@ class RestartNetworkCallback(val context: Context) : ConnectivityManager.Network
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unregister() {
|
||||
Log.d(TAG, "Unregistering ConnectivityManager")
|
||||
connectivityManager?.unregisterNetworkCallback(this)
|
||||
connectivityManager = null
|
||||
registered = false
|
||||
hasInternet = false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private var registered = false
|
||||
private var hasInternet = false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -50,6 +50,8 @@ class StartService : Service() {
|
|||
if (isServiceStarted) {
|
||||
Log.d(TAG, "onDestroy: restarting worker")
|
||||
RestartWorker.run(this, delay = 0)
|
||||
} else {
|
||||
networkCallback.unregister()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue