Android 两种轮询的简单写法,供大家参考,具体内容如下
代码语言:javascript复制public void startPolling() {
subscriber = Observable.interval(0, POLLING_INTERVAL, TimeUnit.MILLISECONDS).
doOnNext(new Action1<Long () {
@Override
public void call(Long aLong) {
doPolling().
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Subscriber<String () {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError");
}
@Override
public void onNext(String response) {
handleResponse(response);
}
});
}
}).subscribe();
}
public void stopPolling() {
if (!subscriber.isUnsubscribed()) {
subscriber.unsubscribe();
}
}
private Observable<Param doPolling() {
return Observable.create(new Observable.OnSubscribe<Param () {
@Override
public void call(Subscriber<? super Param subscriber) {
//do work
subscriber.onNext(response);
subscriber.onCompleted();
}
});
}
在Activity的生命周期里分别调用start和stop方法,解除轮询绑定,避免内存泄漏。
其它简单的轮询方法还有利用handler的postDelay机制实现
代码语言:javascript复制@Override
public void handleMsg(Message msg) {
switch (msg.what) {
case MSG_POLLING:
doPolling(false);
break;
...
...
}
}
private void doPolling(Boolean isFirst) {
if(isFirst) {
mHandler.removeMessages(MSG_POLLING);
mHandler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL);
return;
}
doWork(); //asyn network
mHandler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL);
}
以上就是本文的全部内容,希望对大家的学习有所帮助。