1.实现 ConnectivityManager.NetworkCallback() 的接口,并重写你需要的方法~~我重写的是当网络断开的时候的方法
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class NetWorkCallback(var mContext: Context, var resources: Resources) :
ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
super.onLost(network)
// 断网的时候,你需要做的事情,比如弹出toast~
}
}
2.注册它
private var mNetWorkCallback: NetWorkCallback? = null
// 我在fragment的onCreateView()方法里面调用的initNetWorkTrack()
private fun initNetWorkTrack() {
context?.let {
mNetWorkCallback = createNetWorkMonitor(it)
val request = NetworkRequest.Builder().build()
val manager = it.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager?
mNetWorkCallback?.let { mNetWorkCallback ->
manager?.registerNetworkCallback(request, mNetWorkCallback)
}
}
}
private fun createNetWorkMonitor(context: Context): NetWorkCallback {
return NetWorkCallback(context, resources)
}
3.因为我目前不了解他的回收机制,所以我手动在fragment的onDestroy()里面回收掉
override fun onDestroy() {
super.onDestroy()
mNetWorkCallback = null
}
注意: 上述操作因为我是在fragment里面用,所以都是基于fragment来介绍的。在activity里面同样可以用,比如再在onCreate()里面调用initNetWorkTrack()方法,在activity的onDestroy()里面回收掉~~~
|