- 引入庫
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,雖然是連接上了,但是訪問網絡其實是訪問不了,還需要經過認證后才能訪問。
-
現在能快速檢測到網絡連通性了,下一步怎樣才能檢測網絡的延時呢?不知道有沒有簡單易用的接口。