Skip to content

Instantly share code, notes, and snippets.

@aenonGit
Created October 2, 2018 09:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aenonGit/cbc9c02b6d005746bc181ac5ee9c65f5 to your computer and use it in GitHub Desktop.
Save aenonGit/cbc9c02b6d005746bc181ac5ee9c65f5 to your computer and use it in GitHub Desktop.
Check the connectivity status in Android
class ConnectivityChangeReceiver (val listener : ConnectivityEventsListener?) : BroadcastReceiver() {
interface ConnectivityEventsListener {
fun onConnected() {}
fun onConnecting() {}
fun onDisconnected() {}
fun onDisconnecting() {}
fun onSuspended() {}
fun onUnknown() {}
}
override fun onReceive(context: Context, intent: Intent) {
val netInfo: NetworkInfo? = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
when (netInfo?.state) {
NetworkInfo.State.CONNECTED -> listener?.onConnected()
NetworkInfo.State.CONNECTING -> listener?.onConnecting()
NetworkInfo.State.DISCONNECTED -> listener?.onDisconnected()
NetworkInfo.State.DISCONNECTING -> listener?.onDisconnecting()
NetworkInfo.State.SUSPENDED -> listener?.onSuspended()
NetworkInfo.State.UNKNOWN -> listener?.onUnknown()
}
}
fun register(context: Context) : ConnectivityChangeReceiver{
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(this, intentFilter)
return this
}
fun unregister(context: Context) : ConnectivityChangeReceiver {
context.unregisterReceiver(this)
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment