ReactiveNetwork
介绍:
ReactiveNetwork是一个监听网络连接状态与WiFi信号强度的库,使用RxJava Observable实现。RxJava 1.0.+ 与 RxAndroid 1.0.+,min sdk version = 9
运行效果:
使用说明:
公共API中有两个RxJava Observable:
Observable<ConnectivityStatus> observeConnectivity(final Context context)
Observable<List<ScanResult>> observeWifiAccessPoints(final Context context)
监听连接状态
ConnectivityStatus可以有以下值:
public enum ConnectivityStatus {
WIFI_CONNECTED("connected to WiFi"),
MOBILE_CONNECTED("connected to mobile network"),
OFFLINE("offline");
...
}
我们可以通过observeConnectivity(context) 方法观察ConnectivityStatus,如下:
new ReactiveNetwork().observeConnectivity(context)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
... // anything else what you can do with RxJava
.subscribe(new Action1<ConnectivityStatus>() {
@Override public void call(ConnectivityStatus connectivityStatus) {
// do something with connectivityStatus
}
});
我可以通过RxJava的filter(...) 方法响应状态的变化。isEqualTo(final ConnectivityStatus... statuses) 和 isNotEqualTo(final ConnectivityStatus... statuses)方法位于ConnectivityStatus中。
new ReactiveNetwork().observeConnectivity(context)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.filter(ConnectivityStatus.isEqualTo(ConnectivityStatus.WIFI_CONNECTED))
.subscribe(new Action1<ConnectivityStatus>() {
@Override public void call(ConnectivityStatus connectivityStatus) {
// do something with connectivityStatus, which will be WIFI_CONNECTED
}
});
监听WiFi接入点
我们可以通过observeWifiAccessPoints(context) 方法监听WiFi接入点。每次WiFi接入点信号强度发生改变的时候,Subscriber都会被调用(通常发生在用户移动设备的时候)。我们可以如下操作:
new ReactiveNetwork().observeWifiAccessPoints(context)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
... // anything else what you can do with RxJava
.subscribe(new Action1<List<ScanResult>>() {
@Override public void call(List<ScanResult> scanResults) {
// do something with scanResults
}
});
下载
可以通过Maven添加依赖:
<dependency>
<groupId>com.github.pwittchen</groupId>
<artifactId>reactivenetwork</artifactId>
<version>0.0.1</version>
</dependency>
或者通过Gradle:
dependencies {
compile 'com.github.pwittchen:reactivenetwork:0.0.1'
}
已下载
0