feat: add ConnectivityReceiver for network state monitoring
This commit is contained in:
parent
c11a26c09e
commit
c035181d8d
1 changed files with 32 additions and 0 deletions
|
|
@ -0,0 +1,32 @@
|
|||
package com.traccar.traccar_client.network
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
|
||||
class ConnectivityReceiver(
|
||||
private val onConnectivityChange: (Boolean) -> Unit
|
||||
) : BroadcastReceiver() {
|
||||
|
||||
private var isNetworkAvailable = false
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val newNetworkState = isNetworkAvailable(context)
|
||||
if (newNetworkState != isNetworkAvailable) {
|
||||
isNetworkAvailable = newNetworkState
|
||||
onConnectivityChange(isNetworkAvailable)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun isNetworkAvailable(context: Context): Boolean {
|
||||
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue