Created
March 31, 2018 17:46
-
-
Save AndroidKiran/045bd5a0030fca85e455304c2e88b9ed to your computer and use it in GitHub Desktop.
NetworkLiveData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class NetworkLiveData constructor(private val context: Context?) : LiveData<Boolean>() { | |
| private lateinit var networkConnectionBroadcastReceiver: NetworkConnectionBroadcastReceiver | |
| override fun onActive() { | |
| registerReceiver() | |
| } | |
| override fun onInactive() { | |
| unRegisterReceiver() | |
| } | |
| private fun registerReceiver() { | |
| context?.let { | |
| val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) | |
| networkConnectionBroadcastReceiver = NetworkConnectionBroadcastReceiver() | |
| it.registerReceiver(networkConnectionBroadcastReceiver, intentFilter) | |
| } | |
| } | |
| private fun unRegisterReceiver() { | |
| context?.let { | |
| it.unregisterReceiver(networkConnectionBroadcastReceiver) | |
| } | |
| } | |
| inner class NetworkConnectionBroadcastReceiver : BaseBroadcastReceiver() { | |
| private fun isInternetAvailable(context: Context?): Boolean { | |
| return try { | |
| val cm = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
| val activeNetwork = cm.activeNetworkInfo | |
| activeNetwork != null && activeNetwork.isConnectedOrConnecting | |
| } catch (exception: Exception) { | |
| false | |
| } | |
| } | |
| override fun onReceive(context: Context?, intent: Intent?) { | |
| if (intent?.action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { | |
| postValue(isInternetAvailable(context)) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment