LifecycleObserver
就像名字上说的,它是用于观察宿主的生命周期,这里的宿主指的是Activity
或Fragment
。可以通过实现LifecycleObserver
接口,在方法上添加@OnLifecycleEvent(Lifecycle.Event.ON_XXX)
注释,当生命周期回调到相应的生命周期的时候,就会调用上面的方法。这是管理内容泄露的一个很好的方法,同时这也是生命周期的一个切面。
class ConnectivityChecker(private val connectivityManager: ConnectivityManager) : LifecycleObserver {
private val _connectedStatus = MutableLiveData<Boolean>()
val connectedStatus: LiveData<Boolean>
get() = _connectedStatus
private val connectivityCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
_connectedStatus.postValue(true)
}
override fun onLost(network: Network) {
_connectedStatus.postValue(false)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopMonitoringConnectivity() {
connectivityManager.unregisterNetworkCallback(connectivityCallback)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun startMonitoringConnectivity() {
val activeNetworkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
val connected = activeNetworkInfo != null && activeNetworkInfo.isConnected
_connectedStatus.postValue(connected)
connectivityManager.registerNetworkCallback(
NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(),
connectivityCallback
)
}
}
ConnectivityChecker
代码很简单,在ON_RESUME
时,注册监听器,在ON_PAUSE
的时候取消注册监听器。然后通过connectedStatus
暴露连接状态。下面是调用的代码。
private fun listeningNetChange() {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.apply {
ConnectivityChecker(this).apply {
lifecycle.addObserver(this)
connectedStatus.observe(this@MainActivity, Observer {
if (it) {
//网络已经连接上
} else {
//网络已断开
}
})
}
}
}