ref: dd2ee96d47a98c46ac7ca5a5631e01b8b40a4bea
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 44 |
package ml.adamsprogs.bimba import android.net.ConnectivityManager import android.content.Intent import android.content.BroadcastReceiver import android.content.Context fun isNetworkAvailable(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } class NetworkStateReceiver : BroadcastReceiver() { 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) } } } fun addOnConnectivityChangeListener(listener: OnConnectivityChangeListener) { onConnectivityChangeListeners.add(listener) } fun removeOnConnectivityChangeListener(listener: OnConnectivityChangeListener) { onConnectivityChangeListeners.remove(listener) } interface OnConnectivityChangeListener { fun onConnectivityChange(connected: Boolean) } } |