Skip to content

Commit

Permalink
Merge pull request #4 from davidoskky/main
Browse files Browse the repository at this point in the history
Store the connectivity manager as class variable
  • Loading branch information
ln-12 authored Aug 22, 2022
2 parents afe7731 + 2e76c06 commit 3a62adb
Showing 1 changed file with 8 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import kotlinx.coroutines.withContext
actual class ConnectivityStatus(private val context: Context) {
actual val isNetworkConnected = MutableStateFlow(false)

private val connectivityManager: ConnectivityManager? = null
private var connectivityManager: ConnectivityManager? = null
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
Log.d("Connectivity status", "Network available")
Expand Down Expand Up @@ -49,13 +49,14 @@ actual class ConnectivityStatus(private val context: Context) {

actual fun start() {
try {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

if (connectivityManager == null) {
connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// API 24 and above
connectivityManager.registerDefaultNetworkCallback(networkCallback)
connectivityManager?.registerDefaultNetworkCallback(networkCallback)

val currentNetwork = connectivityManager.activeNetwork
val currentNetwork = connectivityManager?.activeNetwork

if(currentNetwork == null) {
isNetworkConnected.value = false
Expand All @@ -72,10 +73,10 @@ actual class ConnectivityStatus(private val context: Context) {
}
}.build()

connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
connectivityManager?.registerNetworkCallback(networkRequest, networkCallback)

@Suppress("DEPRECATION")
val currentNetwork = connectivityManager.activeNetworkInfo
val currentNetwork = connectivityManager?.activeNetworkInfo

@Suppress("DEPRECATION")
if(currentNetwork == null || (
Expand Down

0 comments on commit 3a62adb

Please sign in to comment.