当前位置:主页 > 移动开发 > Android代码 >

Android两种轮询的实现方法

时间:2021-10-11 09:50:13 | 栏目:Android代码 | 点击:

Android 两种轮询的简单写法,供大家参考,具体内容如下

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机制实现

@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);
}

您可能感兴趣的文章:

相关文章