Skip to content

Instantly share code, notes, and snippets.

@dmersiyanov
Created May 25, 2022 08:29
Show Gist options
  • Save dmersiyanov/71a4d8a25d0870099865321cc6f24794 to your computer and use it in GitHub Desktop.
Save dmersiyanov/71a4d8a25d0870099865321cc6f24794 to your computer and use it in GitHub Desktop.
ConnectionStateManager help observe network state on android with kotlin flow
import android.annotation.SuppressLint
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
class ConnectionStateManager @Inject constructor(
private val connectivityManager: ConnectivityManager,
) {
private var scope: CoroutineScope? = null
private val connectionStateFlow = MutableSharedFlow<Boolean>(1, 0, BufferOverflow.SUSPEND)
private val connectionsCount = AtomicInteger(0)
fun connectionStateFlow(): Flow<Boolean> =
connectionStateFlow.onEach { Timber.d("Has active connection: $it") }
init {
registerCallBack()
}
fun init(scope: CoroutineScope) {
this.scope = scope
}
@SuppressLint("MissingPermission")
fun hasConnection(): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities: NetworkCapabilities? =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
return when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
} else {
try {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
} catch (e: Exception) {
Timber.w(e)
}
}
notifyObservers()
return false
}
private fun notifyObservers() {
if (scope != null) {
scope?.launch { connectionStateFlow.emit(connectionsCount.get() > 0) }
} else {
Timber.w("Scope hasn't been initialized")
}
}
@SuppressLint("MissingPermission")
private fun registerCallBack() {
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
.build()
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
connectionsCount.incrementAndGet()
notifyObservers()
}
override fun onLost(network: Network) {
super.onLost(network)
connectionsCount.decrementAndGet()
notifyObservers()
}
}
connectivityManager.registerNetworkCallback(request, callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment