NetworkConnectivityChecker: filter onConnected callbacks (several callback if Wifi and LTE is connected)

Also do not use merlinsBeard.isConnected, which return trus even if there is no internet access (ex: with Wifi hotspot)
This commit is contained in:
Benoit Marty 2019-09-17 14:22:08 +02:00
parent 38fc4984fe
commit 73ec0f5a83

View file

@ -18,12 +18,10 @@ package im.vector.matrix.android.internal.network
import android.content.Context import android.content.Context
import com.novoda.merlin.Merlin import com.novoda.merlin.Merlin
import com.novoda.merlin.MerlinsBeard
import im.vector.matrix.android.internal.di.MatrixScope import im.vector.matrix.android.internal.di.MatrixScope
import timber.log.Timber import timber.log.Timber
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import kotlin.collections.ArrayList
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.suspendCoroutine
@ -35,23 +33,31 @@ internal class NetworkConnectivityChecker @Inject constructor(context: Context)
.withDisconnectableCallbacks() .withDisconnectableCallbacks()
.build(context) .build(context)
private val merlinsBeard = MerlinsBeard.Builder().build(context) private val listeners = Collections.synchronizedSet(LinkedHashSet<Listener>())
private val listeners = Collections.synchronizedList(ArrayList<Listener>())
// True when internet is available
private var hasInternetAccess = false
init { init {
merlin.bind() merlin.bind()
merlin.registerDisconnectable { merlin.registerDisconnectable {
Timber.v("On Disconnect") if (hasInternetAccess) {
val localListeners = listeners.toList() Timber.v("On Disconnect")
localListeners.forEach { hasInternetAccess = false
it.onDisconnect() val localListeners = listeners.toList()
localListeners.forEach {
it.onDisconnect()
}
} }
} }
merlin.registerConnectable { merlin.registerConnectable {
Timber.v("On Connect") if (!hasInternetAccess) {
val localListeners = listeners.toList() Timber.v("On Connect")
localListeners.forEach { hasInternetAccess = true
it.onConnect() val localListeners = listeners.toList()
localListeners.forEach {
it.onConnect()
}
} }
} }
} }
@ -80,7 +86,7 @@ internal class NetworkConnectivityChecker @Inject constructor(context: Context)
} }
fun isConnected(): Boolean { fun isConnected(): Boolean {
return merlinsBeard.isConnected return hasInternetAccess
} }
interface Listener { interface Listener {