- 引入库
implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.8'
- 监听网络连接变更
ReactiveNetwork.observeNetworkConnectivity(context).subscribeOn(Schedulers.io())// ... // anything else what you can do with RxJava.observeOn(Schedulers.computation()).subscribe { connectivity: Connectivity ->// do something with connectivity// you can call connectivity.state();// connectivity.type(); or connectivity.toString();Log.i(TAG, "onRecv1 connectInfo: $connectivity")}
它会持续监听网络连接的变动,直到调用 dispose()接口。
- 监听服务器连通性
val settings = InternetObservingSettings.builder().host("http://connectivitycheck.platform.hicloud.com/generate_204").build()ReactiveNetwork.observeInternetConnectivity(settings).subscribeOn(Schedulers.io())// ... // anything else what you can do with RxJava.observeOn(Schedulers.computation()).subscribe { isConnectedToInternet ->Log.i(TAG, "onRecv2(generate_204) isconnect: $isConnectedToInternet")}
-
如果使用默认的 InternetObservingSettings, 它会定时2秒检测google服务器的204接口,在大陆是连接不了了。幸好还有很多互联网公司也提供了这样的204接口,这里连接华为的 generate_204 接口。
-
为什么要这样判断呢,因为很多公共wifi,虽然是连接上了,但是访问网络其实是访问不了,还需要经过认证后才能访问。
-
现在能快速检测到网络连通性了,下一步怎样才能检测网络的延时呢?不知道有没有简单易用的接口。