Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store the connectivity manager as class variable #4

Merged
merged 2 commits into from
Aug 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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