ref: b80c6886e9aef8312e571f34644bfaeb86f41200
app/src/main/java/ml/adamsprogs/bimba/NetworkStateReceiver.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package ml.adamsprogs.bimba import android.net.ConnectivityManager import android.content.Intent import android.content.BroadcastReceiver import android.content.Context class NetworkStateReceiver : BroadcastReceiver() { private val onConnectivityChangeListeners = HashSet<OnConnectivityChangeListener>() override fun onReceive(context: Context, intent: Intent) { if (intent.extras != null) { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val ni = connectivityManager.activeNetworkInfo if (ni != null && ni.isConnectedOrConnecting) { for (listener in onConnectivityChangeListeners) listener.onConnectivityChange(true) } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, java.lang.Boolean.FALSE)) { for (listener in onConnectivityChangeListeners) listener.onConnectivityChange(false) } } } interface OnConnectivityChangeListener { fun onConnectivityChange(connected: Boolean) } companion object { lateinit var manager: ConnectivityManager fun init(context: Context) { manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager } fun isNetworkAvailable(): Boolean { val activeNetworkInfo = manager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } } } |