Skip to content

Instantly share code, notes, and snippets.

@BuiVanNam
Last active October 7, 2020 09:19
Show Gist options
  • Save BuiVanNam/82a8c457038a39a99a95c6ec2d8cbbe2 to your computer and use it in GitHub Desktop.
Save BuiVanNam/82a8c457038a39a99a95c6ec2d8cbbe2 to your computer and use it in GitHub Desktop.
Demo Lifecycle-Aware use LifecycleObserver
class NetworkConnectLifecycle(private val context: Context, private val lifecycle: Lifecycle) :
LifecycleObserver,
ConnectivityManager.NetworkCallback() {
private val mConnectActivityManager: ConnectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var networkChange: ((Boolean) -> Unit)? = null
init {
lifecycle.addObserver(this)
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
networkChange?.invoke(true)
}
override fun onLost(network: Network) {
super.onLost(network)
networkChange?.invoke(false)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
if (!context.isOnline()) {
networkChange?.invoke(false)
}
mConnectActivityManager.registerDefaultNetworkCallback(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
mConnectActivityManager.unregisterNetworkCallback(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
lifecycle.removeObserver(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment