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); }
上一篇:Android Studio 3.6 调试 smali的全过程
栏 目:Android代码
本文标题:Android两种轮询的实现方法
本文地址:http://www.codeinn.net/misctech/179573.html