Bimba.git

ref: b96ea951adb4c6659f64668075b3e49eeb771c4d

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
45
46
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)
            }
        }
    }

    fun addOnConnectivityChangeListener(listener: OnConnectivityChangeListener) {
        onConnectivityChangeListeners.add(listener)
    }

    fun removeOnConnectivityChangeListener(listener: OnConnectivityChangeListener) {
        onConnectivityChangeListeners.remove(listener)
    }

    interface OnConnectivityChangeListener {
        fun onConnectivityChange(connected: Boolean)
    }

    companion object {
        fun isNetworkAvailable(context: Context): Boolean {
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            return activeNetworkInfo != null && activeNetworkInfo.isConnected
        }
    }
}